Preprocessor Directives
Preprocessor directives supply the compiler with additional information about regions of code.
The most common preprocessor directives are the conditional directives, which provide a way to include or exclude regions of code from compilation.
In this class, the statement in Foo is compiled as conditionally dependent upon the presence of the DEBUG symbol.
#define DEBUG class MyClass { int x; void Foo() { #if DEBUG Console.WriteLine("Testing: x = {0}", x); #endif } ... }
#define symbol | Defines symbol |
#undef symbol | Undefines symbol |
#if symbol [operator symbol2]… | symbol to test operators are ==, !=, &&, and || followed by #else, #elif, and #endif |
#else | Executes code to subsequent #endif |
#elif symbol [operator symbol2] | Combines #else branch and #if test |
#endif | Ends conditional directives |
#warning text | text of the warning to appear in compiler output |
#error text | text of the error to appear in compiler output |
#pragma warning [disable | restore] | Disables/restores compiler warning(s) |
#line [ number [“file”] | hidden] | number specifies the line in source code; file is the filename to appear in computer output; hidden instructs debuggers to skip over code from this point until the next #line directive. |
#region name | Marks the beginning of an outline |
#endregion | Ends an outline region |
Conditional Attributes
An attribute decorated with the Conditional attribute will be compiled only if a given preprocessor symbol is present.
//file1.cs #define DEBUG using System; using System.Diagnostics; [Conditional("DEBUG")] public class TestAttribute : Attribute {} //file2.cs #define DEBUG [Test] class Foo { [Test] string s; }
The compiler will only incorporate the [Test] attributes if the DEBUG symbol is in
scope for file2.cs.
Pragma Warning
The compiler generates a warning when it spots something in your code that seems
unintentional but it does not prevent the code from compiling.
Compiler warnings can be extremely valuable in spotting bugs.
Pragma Warning is used to suppress warning. Omitting the number in the #pragma warning directive disables or restores all warning codes.
public class Foo { static void Main() {} #pragma warning disable 414 static string Message = "Hello"; #pragma warning restore 414 }