Suppress Code Analysis Warnings In Code
Code analysis provides a way of making sure our assemblies don’t violate the programming and design rules set forth in the Microsoft .NET Framework Design Guidelines (including issues related to Globalization, Security, Performance, Portability, and many more). We can run code analysis from the IDE and from MSBuild. To do it, we first have to turn on Code Analysis from within the IDE. To do it we have to open the project properties, and in the Project designer, we should select the Code Analysis tab and check the Enable Code Analysis on Build checkbox.
By default, violations will only appear as warnings in the Error List window. Alternatively, you can flag violations as errors by placing a check in the Treat Warning as Error column for a particular rule.
Now, when code analysis is enabled we can build our project. For example, I wrote Foo method that never used. After I built the project I got the following warning:
I got CA1811 warning, which means that the code analysis engine found that this method never used. I can use System.Diagnostics.CodeAnalysis.SuppressMessage attribute to suppress this warning:
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Performance",
"CA1811:AvoidUncalledPrivateCode")]
private static void Foo(int num1, int num2)
{
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
if (numbers[num1] == num2)
{
numbers[num1] = 1;
}
}
To use this attribute we should add System.Diagnostics.CodeAnalysis namespace. The SuppressMessage class got 2 parameters:
- The category identifying the classification of the attribute. (Microsoft.Performance in our case)
- The identifier of the static analysis tool rule to be suppressed. (CA1811:AvoidUncalledPrivateCode in our case).
After adding this attribute, the warning disappeared…