Rule Suppressions

Starting with StyleCop 4.3.2, it is possible to suppress the reporting of rule violations by adding suppression attributes within the source code. The syntax for these suppressions is similar to that for Visual Studio Code Analysis, or FxCop. For more information about Code Analysis suppressions, see the following article: In Source Suppressions Overview.

StyleCop rule suppressions are registered in code using the SuppressMessage attribute. The SuppressMessage attribute is a conditional attribute, which is included in the IL metadata of your managed code assembly only if the CODE_ANALYSIS compilation symbol is defined at compile time.

We recommend that you use in-source suppressions on debug or check-in builds, in order to eliminate the possibility of mistakenly shipping the in-source suppression metadata and compromising execution or performance because of the metadata bloat. Since StyleCop analyzes the source code directly, there is no need for these attributes to be compiled into the assembly.

The SuppressMessage attribute has the following format:

[SuppressMessage( "Rule Category" , "Rule Id" , "Justification" )]

Where:

  • Rule Category - The StyleCop rule namespace in which the rule is defined. For example, Microsoft.StyleCop.CSharp.DocumentationRules
  • Rule Id - The identifier for the rule, using the format shortname:longname. For example, SA1600:ElementsMustBeDocumented
  • Justification - The text that is used to document the reason for suppressing the message.

The SuppressMessageattribute also takes the following optional parameters. These parameters are completely ignored by StyleCop and do not need to be filled in for StyleCop suppressions.

  • Message Id
  • Scope
  • Target

SuppressMessage Usage

StyleCop violations are suppressed at the level to which an instance of the SuppressMessage attribute is applied. The purpose of this is to tightly couple the suppression information to the code where the violation occurs.

For example, a StyleCop SuppressMessage attribute placed on a class will suppress the rule for all contents of the class. The same attribute placed on a method will only suppress the rule within the method.

Global Suppressions

StyleCop does not support the notion of global suppressions or file-level suppressions. Suppressions must be placed on a code element.

Examples:

The following code suppresses the ElementsMustBeDocumented rule for the given class and all its contents:

[SuppressMessage("Microsoft.StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented")]
public class MyUndocumentedClass
{
public void MyUndocumentedMethod
{
}
}