Tuesday, April 27, 2010

Conditional Compilation using C#

Consider a code where you need to enable some lines based on a condition. Let’s say all the debug logs should not be shipped along with the product but you need the log information when you develop or test the application. If you are using ASP.Net you can make use of trace or Debug. how do you do that if you need to log something from the dll  ? What is the easy method to do this?


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