In this article we will see when and how to use some of the preprocessor directives in C# programming.Let's take a small break from Design Patterns and learn a small, interesting and somewhat unnoticed concept.What is a Preprocessor Directive?Preprocessor directives are commands that are interpreted by the compiler and affect the output or behavior of the build process. We will see some of them now.
#region and #endregionSometimes we come across a situation where we want to give a particular group of code a name.
#region MathsLogic
int number1 = 0;
int number2 = 0;
Console.WriteLine("Enter 2 numbers");
string strNumber1 = Console.ReadLine();
string strNumber2 = Console.ReadLine();
int.TryParse(strNumber1, out number1);
int.TryParse(strNumber2, out number2);
int Sum = number1 + number2;
Console.WriteLine("Your Sum is " + Sum);
#endregion
Use of regions makes code readable, intuitive and easy to manage (Visual Studio, for example, allows you to easily hide or display regions).#define
#define Test1#define Test2 using System;using System.Collections.Generic;using System.Linq;#if, #elif, #else, #endifSometimes we do write some code which is just needed during development mode, or required only in some conditions.In the above statement not needed means even not required to compile.We can do this with the help of these four directives.#if Test1 Console.WriteLine("Test1 Defined");#elif Test2 Console.WriteLine("Test1 not Defined but Test2 Defined");#else Console.WriteLine("Both Test1 and Test2 are undefined");#endifHere Test1 and Test2 are compilation symbols created using #define.
The main difference between working this way and using traditional if…else with global variables is that here the code won't even be compiled if it finds the symbol is not defined.Download the attached samples for a practical demonstration.Thanks for reading,Hope you enjoyed and stay tuned for more such articles. Comments are always welcome.