.NET 1.1+C# #warning and #error Directives
In some situations you may wish to purposefully cause compilation errors or warnings in your code. For example, a warning indicating that you are compiling in debug mode or an error for deprecated code. These can be added using preprocessor directives.
Preprocessor Directives
Preprocessor directives are commands that are interpreted by the compiler and affect the output or behaviour of the build process. In this article we will examine two of these directives, #warning and #error. These directives add warnings and errors to the compilation process.
#warning Directive
There are many reasons that you may wish to output a user-defined warning during the compilation of your code. Some possible motives are:
- Your code can be compiled in debug or release mode depending upon the presence of defined symbols. However, if you are compiling in debug mode you wish to output a warning that the debug version should not be shipped.
- Your software has multiple versions, such as bronze, silver and gold. If you have mistakenly defined symbols for more than one version, you wish to output a warning explaining this error.
- You wish a warning to be displayed because some elements of the code have been deprecated.
In such circumstances, and many more, you can add the #warning preprocessor directive to your code to output a custom warning during compilation. The directive is simply added to the code with the desired warning text appended. The following example demonstrates this by adding a warning when the program is compiled in debug mode. NB: If you are using Visual Studio, this warning appears when compiling in debug mode but not in release mode. If you are using another integrated development environment you may need to define the DEBUG symbol manually.
#if DEBUG
#warning Compiled in DEBUG mode. Do not ship this code.
#endif
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world");
}
}
}
#error Directive
The #error directive is similar to the #warning directive in its function and syntax. However, rather than causing a warning at compile time, #error generates an error. This means that the code will not build successfully when the error is active. To demonstrate, try building the following sample. This example fails to compile because the code incorrectly defines two software edition symbols where only one is permitted.
#define STANDARD_EDITION
#define ADVANCED_EDITION
#if STANDARD_EDITION && ADVANCED_EDITION
#error Check edition symbols, must be either standard or advanced.
#endif
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world");
}
}
}
11 July 2008