About
In this code snippet, we will take a look at preprocessor directives in C#.
Preprocessor directives are statements that get executed before compilation. They are designated by the # sign.
Preprocessor directives can, for example, be useful when debugging code. Suppose we make an if statement that checks whether the program is in debug mode. If so we would enable some diagnostic output otherwise we wouldn’t.
You might ask yourself why can’t I do this using a standard if statement. Well, you can, but that if statement is going to stay in your code. Meanwhile, any preprocessor directives will get executed at compile time and will be removed from the code itself.
Here is a complete list of preprocessor directives.
Let’s look at the code example below to see how to make use of preprocessor directives.
Code:
//Defining a symbol. This must be done before any code is written, else we'll get an error. #define DEBUGMODE using System; namespace Preprocessor_Directives { class Program { static void Main(string[] args) { #if DEBUGMODE Console.WriteLine("Doing testing, debuging stuff...."); #else Console.WriteLine("Hello World"); #endif Console.ReadLine(); } } }