Inline Warning Control

There has been plenty of talk on four of the bigger new features in the C# compiler/language: generics, anonymous methods, iterators, and partial types. There are however several other new features that could use some love as well.

One of them is '#pragma warning'. Using this feature you can disable all warnings or specific ones in a block of code or source file. Here are some examples of it in use:

 #pragma warning disable 78
// Disables warning CS0078 within this block
#pragma warning restore 78
---
#pragma warning disable
// All warnings are disabled in this block
#pragma warning restore
---
#pragma warning disable 78, 1030
// Warnings CS0078 and CS1030 are disabled in this block
#pragma warning restore 78
// Warning CS1030 is disabled in this block (CS0078 is enabled again)
#pragma warning restore
// All warnings are enabled, including CS1030
---
#pragma warning disable
// Disables all warnings for the remainder of this file

A few other things to note:

  • It is not allowed to restore a warning that was disabled via the /nowarn compiler option. Doing so will actually generate another warning (CS1635) which can also be disabled.
  • The scope #pragma warning affects is at most the file it is specified in. It is not global. If you want to disable a warning for all of your source files you should use the /nowarn compiler option instead.
  • Even if the /warnaserror compiler option is enabled, warnings can still be disabled via #pragma warning.

Another new (and even smaller) change in Whidbey is how the /warnaserror option now allows you to specify a list of warnings you'd like to promote to errors or demote back to warnings. For example, you could use the following command line to force all warnings to errors except for CS1030:  

 csc /warnaserror+ /warnaserror-:1030 test.cs

These may not be all that exciting but we've had tons of requests for them internally and externally. If you have any feedback or questions, feel free to send them my way...