C# Error Directive

Pound (#) symbol

#error creates a compilation error. When this directive is reached, your program won't compile. We combine the #if directive with the #error directive to test conditions—and in some cases error out.

Example

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 two defined symbols: A and B. If both of these are defined, we want to force an error so that the program won't compile. This can eliminate problematic combinations of settings.

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

Program that uses #error directive [C#]

#define A
#define B

#if A && B
#error Never define A and B at the same time!
#endif

class Program
{
    static void Main()
    {
    }
}

Using #error without #if. You can actually just use #error directly in a program, but the end result is that the program will never be usable. For this reason, almost all reasonable usages of #error tend to wrap the directive inside an #if block.

Consider #warning

Programming 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, you can consider the #warning directive in place of the #error directive.

Warning Directive

Summary

The C# programming language

The #error directive has a limited but important use in the C# language. It can force an error to occur and compilation to fail in the case of a severely broken configuration. This can reduce the risks or confusion associated with a poor selection of compile-time options.

Directives
.NET