FAQ: Why does FxCop ignore my in-code (SuppressMessageAttribute) suppressions? [David Kean]

FxCop 1.35 brings with it the ability to suppress messages in code via the use of the SuppressMessage attribute. This allows you to do the following:

    public class PublicKey
    {
        private byte[] _Token;

[...]

[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
        public byte[] Token
{
            get { return (byte[])_Token.Clone(); }
}
}

In the above example, we've suppressed the Properties Should Not Return Arrays violation for the Token property so that FxCop no longer will raise it. There are clear advantages having a suppression applied directly to the offending member or type:

  • Other developers on your team can quickly see that an obvious violation has been suppressed.
  • Unlike in-project suppressions, changes to the namespace, type or signature of a member (ie name, return type, etc) do not require the SuppressMessage attribute to be updated.

When first using in-code suppression, it can be confusing as to why FxCop seems to ignore these attributes. The SuppressMessage attribute is what is called a 'conditional' attribute. A conditional attribute is an attribute that is only included in metadata of your assembly if a certain compilation symbol is defined at compile time. The SuppressMessage attribute itself requires the CODE_ANALYSIS symbol to be present and by default, this is not included in non-team system projects.

To define this symbol is easy, simply do the following:

Visual C# 2005:

  1. In Solution Explorer, right-click your project and choose Properties
  2. In the Properties window, choose the Build tab
  3. In the Conditional compilation symbols text box, enter CODE_ANALYSIS

   -or-

  1. csc /define:CODE_ANALYSIS [...]

Visual Basic 2005:

  1. In Solution Explorer, right-click your project and choose Properties
  2. In the Properties window, choose the Compile tab and click Advanced Compile Options
  3. In the Custom constants text box, enter CODE_ANALYSIS

   -or-

  1. vbc /define:CODE_ANALYSIS=True [...]

Visual C++/CLI 2005:

  1. In Solution Explorer, right-click your project and choose Properties
  2. In the Properties window, expand the Configuration Properties -> C/C++ -> Preprocessor node
  3. In the Preprocessor Definitions text box, add ;CODE_ANALYSIS
  4. Click OK 

   -or-

  1. cl /D CODE_ANALYSIS [...]

Once you have recompiled your assembly, FxCop should now respect any in-code suppressions.

As always, if you have any questions or issues with FxCop or Managed Code Analysis (including the SuppressMessageAttribute) head over to the FxCop forum.