#1,127 – Where to Find Compiler Warning Numbers

You can use #pragma warning to selectively disable certain warnings that occur when compiling your code.

The #pragma warning line requires knowing the specific warning number, which is not displayed in the list of warnings on the Error List tab.


To find the warning number, you need to switch to the Output tab and look at the full text of the warning.  In the example below, we see that the warning about an event that is never used is warning #67.


Once you know the warning number, you can use it with a #pragma warning.

#pragma warning disable 67
        public event EventHandler CanBarkChanged;
#pragma warning restore 67

#509 – Use #pragma warning Directive to Disable Compile-Time Warnings

You typically want to fix any issues raised by the compiler as warnings at compile-time.  For example, the compiler might warning you that you declare a variable, but never use it.  In this case, you’d likely remove the variable declaration entirely.

There are times, however, when the compiler issues a warning about something that you know about and have no intention of “fixing”.  In the example below, we’ve implemented a CanBarkChanged event because it is part of an interface we are implementing, but we never fire the event.  The compiler warns us that we never fire this event.

Since we have no intention of firing the CanBarkChanged event, we can disable warning #67 when compiling this line of code, using the #pragma warning disable and #pragma warning restore directives.  We will then no longer get warning #67 for this line of code.


#118 – Disabling Specific Compiler Warnings

There are times when you knowingly want to include C# code in your program that generates a warning.

For example, the following code will generate a warning at compile time:

 static void Main(string[] args)
     uint x = 0x1234;

The warning appears in the Output window – CS0219: The variable ‘x’ is assigned but its value is never used.

If you’re aware of what this warning means, you don’t intend to change the source code to resolve it, and you want to no longer see the warning for this particular line, you can use the #pragma warning directive.  Place the directive immediately above the offending line and reference warning #219.

 static void Main(string[] args)
#pragma warning disable 219
     uint x = 0x1234;

You’ll no longer get warning #219 for this line when you compile.