Saturday, June 5, 2010

How to Suppress .NET Warnings

In my current project, there are several warnings (C#) that are caused by several lines of code resulting from CSLA inheritance. Those warnings are basically about a local variable that is assigned but never used. Completely harmless and localized.Or on a different scenarios, you may run a Code Analysis and it returns a bunch or warnings.

For the longest time, I just ignore those warnings. But when I moved from VS 2008 to VS 2010 and to .NET 4, I thought that now is the right time to suppress those warnings.

There are several ways to remove/suppress warnings:
  1. Obviously, the warnings are there for a reason, and maybe that reason is valid. Maybe you declare a variable that is never used and should be removed, or make some methods "static", or unreachable code, etc etc. If these warnings are valid - then you should fix your code.
  2. Please do not go do this step if you have not done #1 thoroughly. OK, now you decided that the code is correct but the warning is still there and you want to suppress it. In most cases, you can right click on the warning in the list and select "Suppress Message" and pick whether you want to suppress it inline in the code or put them in a separate GlobalSuppression.cs file. Only the warnings that have a "CA" number or "CheckId" can be suppress this way. Warnings that do not have CheckId must be handled in a different manner - see #3.
  3. Using #pragma. Read this for MSDN explanation of pragma. Basically, with pragma, you do this: #pragma warning [disable|restore] [CheckId]. The CheckId must not contain the "CA" prefix. 
There you go ... now we can sleep a bit better knowing we have less warnings in our code. 

1 comment:

Anonymous said...

Thank you. precise information :)