How to suppress compiler warning using #pragma warning directives in Visual Studio ?

Sometimes during development you may need to avoid the unnecessary compiler warnings to show in warning window. Though it’s not recommended to suppress the warning explicitly, but during some debugging and analysis of code you may want to hide them for time being. In this post I have explained how you can hide the unwanted warning explicitly by specifying the warning number.

To suppress the warning you need to use #pragma warning directives in your code. Below is the syntax for the same.

#pragma warning disable <warning-Numbers>

[Line of Code ]

Let’s consider you are having the below code block and you want to suppress the warning messages.

1

If you are going to build the above code, you will find the below warning messages.

2

Now, you can use #pragma warning directives to disable those compilation warning. You have to mention the warning number along with the directives. If you want to suppress multiple warning you have to use the coma separated warning number.

3

This addition of warning disable directives will remove all the specified compilation warning.

4

To suppress warnings you have to mention the warning number. So, you have to make sure you are providing the correct warning number. You can find out the warning number from the output window while building the application.

5

Similarly you can use #pragma warning restore <warning-lists> to restore the compilation warning message.

note If there is no warning number provided with the #pragma warning directives, it will suppress all the warnings.


Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

One Comment to “How to suppress compiler warning using #pragma warning directives in Visual Studio ?”

Comments are closed.