C# Fundamentals - Pre-Processor Directives

C# Fundamentals - Pre-Processor Directives

The pre-processor directives give instruction to the compiler to process some information before the actual compilation starts.
All pre-processor directives begin with #, and only white-space characters may appear before a pre-processor directive on any given line.
As pre-processor directives are not statements, they do not require a semi-colon (;) to the placed at the end of the line.
C# compiler does not have a separate pre-processor; however, the directives are processed as if there was one. In C# the pre-processor directives are used to help in conditional compilation.
Unlike C and C++ directives, they are not used to create macros. So as they are less flexible in what they can do in C++; they are mostly used for conditional compilation ( whether a set of lines of code would be compiled or not ). A pre-processor directive must be the only instruction on a line.
There are 6 main directives used in C#, they are:
  • #if
  • #else
  • #elif
  • #endif
  • #define
  • #undef
#if, #else, #elif & #endif
using System;
public class TestClass
{
    static void Main()
    {
#if (DEBUG && !BITSHIFT)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && BITSHIFT)
        Console.WriteLine("BITSHIFT is defined");
#elif (DEBUG && BITSHIFT)
        Console.WriteLine("DEBUG and BITSHIFT are defined");  
#else
        Console.WriteLine("DEBUG and BITSHIFT are not defined");
#endif
    }
}
DEBUG & BITSHIFT are not defined
As you can see, the DEBUG & BITSHIFT symbol is not defined.
#define & undef
#define BITSHIFT
#define DEBUG
#undef DEBUG
using System;
public class TestClass
{
    static void Main()
    {
#if (DEBUG && !BITSHIFT)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && BITSHIFT)
        Console.WriteLine("BITSHIFT is defined");
#elif (DEBUG && BITSHIFT)
        Console.WriteLine("DEBUG and BITSHIFT are defined");  
#else
        Console.WriteLine("DEBUG and BITSHIFT are not defined");
#endif
    }
}
BITSHIFT is defined
Now we have defined BITSHIFT but DEBUG was not. Even though we defined it, we undefined right after that.
In a practical use-case scenario you would define compiler options for these defines and you might want to undefine those compiler set define statements, That's where we use 'undef'.
Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.
If you have any questions that you might have about shaders, C# or Unity development in general don't be shy and leave a message on my facebook page or down in the comments.
For More C# Tutorials, go HERE.
For Unity Tutorials, go HERE.