C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
When this directive is reached, your program won't compile. We combine the #if directive with the #error directive to test conditions. With #warning we force a compiler warning.
Error. To begin, you can specify an error by starting a line with the #error directive and then ending the string with a new line. In this program, we have defined two symbols at the top: A and B.
And: If both of these are defined, we want to force an error so that the program won't compile.
Tip: This approach to compiler errors can eliminate problematic combinations of settings.
C# program that uses error directive #define A #define B #if A && B #error Never define A and B at the same time! #endif class Program { static void Main() { } }
Also, you can use #error directly in a program, but the end result is that the program will never be usable. For this reason, most reasonable usages of #error tend to wrap the directive inside an #if block.
Tip: Another related directive you can employ is the #warning directive. This does not force a fatal error in compilation.
Instead: It just causes a nagging warning. Depending on the severity of the compile-time problem, consider the #warning directive.
Warning. The #warning directive 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.
You can use the #warning directive by placing the #warning text followed by the text warning, terminated by a newline. You do not need quotation marks surrounding the text. When this program is compiled, you can see the Error List.
C# program that uses warning directive using System.Diagnostics; #warning Don't run this program. class Program { static void Main() { #warning Get back to work. Process.Start("http://www.reddit.com/"); } }
Conditional warnings. It is also possible to use conditional warnings by wrapping #if and #endif directives around the #warning directive. This possible example is not shown in the program.
Tip: You can see further examples of #warning and #error in section 2.5.5 of the C# specification annotated third edition.
Note: The #warning directive is different from an Assert call. It is triggered at compile-time, not at run-time.
Note 2: You cannot warn with this directive on the run-time aspects of your program. The directive is processed too early.
Summary. With #error and #warning we influence compiler behavior. These directives have a limited but important use. We can force an error to occur and compilation to fail. This helps in the case of a severely-broken configuration.