C# Preprocessor Directives

C# Code Snippets Preprocessor Directives
Share:

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();
        }
    }
}

Resulting output:

DEBUGMODE is defined.
DEBUGMODE is commented out.
Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger