I am a big fan of using Code Analysis (formerly FXCop) in my Visual Studio projects to help catch issues. Recently I ran across a CA2208 warning that I needed to think about. Usually these are simple results of refactoring or forgetting to include the argument name in the ArgumentNullException or ArgumentOutOfRangeException. This one, however, was a little different. The value was passed to the exception constructor and the name was correct.

The following code reproduces the issue (note this is C# 6 code written in the VS 2015 Preview leveraging the new nameof keyword):

private static void Foo(string bar, string baz)
{
    if (bar == null)
        throw new ArgumentNullException(nameof(bar));

    Task.Run(() =>
    {
        if (baz == null)
            throw new ArgumentNullException(nameof(baz));

    });
}

The reason being is that rule checks to make sure the name being passed to the constructor of the exception matches a parameter of the current method. However, the code that gets generated for the delegate doesn't pass baz as a parameter, rather it is a public field on the generated class. The code for the generated class essentially looks like this:

[CompilerGenerated]
private sealed class <>c__DisplayClass0
{
    public string baz;
    internal void <Foo>b__1()
    {
        bool flag = this.baz == null;
        if (flag)
        {
            throw new ArgumentNullException("baz");
        }
    }
}

So I have come to the conclusion to simply suppress this message for the time being. Hopefully with the new Roslyn analysis capabilities minor issues like these can be completely avoided.