C# Suppress Compilation Warnings with #pragma or the SuppressMessage Attribute

Although one would hope that you wouldn’t have to do so very often, sometimes it is useful to explicitly disable code analysis warnings within your application. For example, you could suppress warnings around references to obsolete methods that must be called. Two ways of making this happen are to use either the preprocessor directive “#pragma warning” or to use the SuppressMessageAttribute.

Here’s how you could use the #pragma warning preprocessor directive to suppress an obsolete code warning:

// Disable warning for obsolete call
#pragma warning disable 612, 618
#pragma warning restore 612, 618
// Warnings are re-enabled

And here is how you could use the SuppressMessage attribute to achieve a similar result:

[SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "isChecked")]

There is of course the argument that by suppressing those messages you won’t remember that they are there and won’t then refactor them out of your application, but…
Hope this helps!

This entry was posted in Attributes, C#, MSBuild, Visual Studio. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *