简体   繁体   中英

Code Analysis does not show CA1804 warning despite unused local string variable in C# (VS2010 Premium)

I've got the following code that does not produce an CA1804 warning (declared variable is never used) from code analysis (VS2010 Premium):

...
if( boolVariable )
{
    string errorText = "Bla Bla Bla"; // Never used
    ErrorProvider.SetError( SomeControl, "Some Warning" );
}
else
{
    string errorText = "Acme Acme Acme"; // Used below
    ErrorProvider.SetError( SomeControl, errorText );
}
...

When I remove the ErrorProvider.SetError( ... ) lines, the CA1804 warning is shown, but why is this not the case in the code sample above?

(Btw: The code itself is not too great and just shown to illustrate my question.)

Any ideas what might be causing this behaviour? I guess this might be down to the fact that the IL code is optimised in a way that puts the declaration outside the if , which in turn would mean that the warning should indeed not show up in an example like the one above, but I'm not sure whether this is true.

Thanks in advance

G.

That would be because of an optimization performed by the C# compiler. In the generated IL, the variable declaration is hoisted out of the if block:

string errorText;
if (boolVariable)
{
    errorText = "Bla Bla Bla";
    this.ErrorProvider.SetError(this.SomeControl, "Some Warning");
}
else
{
    errorText = "Acme Acme Acme";
    this.ErrorProvider.SetError(this.SomeControl, errorText);
}

Removing only the second SetError call is actually sufficient to trigger CA1804.

BTW, the C# compiler should have issued a CS0219 warning for this, which you apparently ignored. I would very strongly recommend treating compiler warnings as errors if you're remotely interested in code quality, which you presumably are if you are running Code Analysis. Why add an additional screening tool before you take maximum advantage of the one you are already using?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM