Let’s look at C# #IF directive and see how we can make use of it.
When the C# compiler encounters #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. i.e if my code contains something below
namespace FirstConsole
{
class Program
{
static void Main(string[] args)
{
#if DEBUG
Console.WriteLine("My debug entries");
#endif
Console.WriteLine("Program Ends");
Console.ReadKey();
}
}
}
The line Console.WriteLine("My debug entries"); will be compiled only when I build the application in debug mode.
Let’s do this simple test to get the clear understanding. Now I have created console application and placed above code.
I am going to build the application in Debug mode
Here is the result.
Ok. Now let’s change our build mode to release and see the output.
We can also have our own defined symbols and use them for conditional compilation. On the build settings change as below
And change the code as
class Program
{
static void Main(string[] args)
{
#if MYTEST
Console.WriteLine("My debug entries");
#endif
Console.WriteLine("Program Ends");
Console.ReadKey();
}
}
Check the result now!!
Ok now let’s look at another advantage. I want ship a product with 2 different versions BASIC and PROFESSIONAL. I need to differentiate some of the functionalities based on the configuration. One way to do this is by keeping system level configuration and check everywhere from the config. We can also do this by using conditional compilation. Here is my sample code snippet
class Program
{
static void Main(string[] args)
{
#if BASICEDITION
Program.MyBsicVersionCall();
#elif PROFESSIONALEDITION
Program.MyBsicVersionCall();
#endif
Console.WriteLine("Program Ends");
Console.ReadKey();
}
static void MyBsicVersionCall()
{
Console.WriteLine("Basic Version");
}
static void MyProfessionalVersionCall()
{
Console.WriteLine("Professional Version");
}
}
Change the conditional compilation symbol and check the result!!
This would definitely help developers to put their debug statements as I used it a lot on my middle layer services and dlls to enable debugging.
No comments:
Post a Comment