A pretty cool feature in .NET 2.0 is the ability knowingly disable a list of warnings using the #pragma directive.
public class foo
// Disable warnings for unused or unassigned fields
#pragma warning disable 0169, 0414
// No warning
// No warning
int b = 0;
// Restore warnings for unused or unassigned fields
#pragma warning restore 0169, 0414
// Warning CS0169 issued
// Warning CS0414 issued
int d = 0;
You can see the effect of using the #pragma directive easily using the command-line C# compiler, csc.exe:
C:\Documents and Settings\kirke\Desktop>csc /t:library test.cs
Microsoft (R) Visual C# 2005 Compiler version 8.00.50215.44
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50215
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.
test.cs(17,9): warning CS0169: The private field ‘foo.c’ is never used
test.cs(19,9): warning CS0414: The private field ‘foo.d’ is assigned but its value is never used
You can see that no warning is issued for fields “a” or “b” due to the #pragma directive. If warning numbers are specified to disable, all warnings are disabled. The same goes for restore numbers, if you don’t specify numbers then all warnings are restored.
This is really useful when you are reworking your code (or rather, reworking someone else’s). For instance, I am a bit anal about warnings, one of the first settings I changed in Visual Studio 2003 was “Treat Warnings As Errors” in the project settings, setting it to “True”, ensuring that all compiler warnings are addressed. I loaded up some code that a customer sent, changed this setting, and located the issue fairly quickly within their code. Once I found the error, I started moving lots of stuff around, but my code wouldn’t compile because I was still treating all warnings as errors. Rather than turn it off, I could localize the warning I wanted to suppress with a #pragma warning disable right before the offending line of code.
In Visual Studio 2003, you really had 1 option: either you treat warnings as errors or you don’t. In Visual Studio 2005, you have a couple more options to control this. Now, you have 3 options for treating warnings as errors: All, None, or Specific Warnings, where you can provide a semi-colon separated list of error numbers. One thing to be sure of when using this technique: if you suppress a warning in the project property setting, you cannot restore it programmatically.