Archive for August, 2006

Suppressing FxCop Messages

Using the latest version (1.35) of FxCop, it is possible to exclude generated warning messages in the source code instead of having to exclude them in the FxCop project file. This is accomplished using the System.Diagnostics.CodeAnalysis.SuppressMessageAttribute class.

To exclude a message, simply mark up the method with the SuppressMessage attribute, declaring both the rule category and the specific rule to exclude:

[SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
public string ConvertToString(object obj)
{
    return obj.ToString();
}

The above example will exclude the "Validate Arguments Of Public Methods" rule from the Design category for the ConvertToString method (although in this contrived example it is probably a bad idea to do so as passing in a null will clearly cause problems).

One extra "tweak" that can be utilised in this scenario is the Justification property. Altering the above code to:

[SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", Justification="I do have a valid reason, honest!")]
public string ConvertToString(object obj)
{
    return obj.ToString();
}

will allow the person excluding a message to provide a reason for doing so in the code, alongside the exclusion. FxCop (v1.35) currently doesn't display this in its output, but will do in the next release (source). It does however output the justification to a generated report if the options are set to output exclusions to the report.

Excluding FxCop messages in the source code has advantages over excluding them in the FxCop project as it demonstrates that the message has been specifically excluded for that particular case, but also will withstand class and namespace changes. It also makes switching from the standalone FxCop to Visual Studio's code analysis an easier process.

In order to allow the SuppressAttribute to work, a CODE_ANALYSIS conditional compilation symbol must be defined for the project. Without this, FxCop will ignore the suppressed attribute and will still generate a warning.

More details can be found on the FxCop blog.

2 comments Permalink August 23rd, 2006 Adrian Banks
Subscribe to this feed Bookmark this post on del.icio.us Digg this post on digg.com Share this post


Calendar

August 2006
M T W T F S S
« Jul   Dec »
 123456
78910111213
14151617181920
21222324252627
28293031  

Posts by Month

Posts by Category

RSS Feeds Feeds

Visitors

Visitor Map