C# Warning Directive

#warning adds a compile-time warning. It is a preprocessing directive in the C# language. It issues warnings—these are shown in Visual Studio in the source file and in the Error List dialog.

Warnings screenshot

Example

First, you can use the #warning directive by placing the #warning text followed by the actual text warning, which is terminated by a newline. You do not need quotation marks surrounding the warning text. When this program is compiled, you can see the Error List as shown above.

Visual Studio Tips

This C# example program shows how to use the #warning directive.

Program that uses #warning directive [C#]

using System.Diagnostics;

#warning Don't ever run this program.

class Program
{
    static void Main()
    {
#warning Get back to work.
	Process.Start("http://slashdot.org/");
    }
}

Result: Two warnings are issued by the compiler.

The C# programming language

Conditional warnings. You can also use conditional warnings by wrapping #if and #endif directives around the #warning directive. This example is not shown in the above program. You can see further examples of #warning and #error in section 2.5.5 of the C# specification annotated third edition.

Summary

The #warning directive is different from an Assert call because it is triggered at compile-time rather than runtime. You cannot warn on the run-time aspects of your program; rather, the directive is processed before the program is transformed into the intermediate language, while still in lexical form.

Directives
.NET