Sunday, January 29, 2012

Conditional compilation in C#

Programmers need to debug, which sometimes requires identification of points in your program where a programmer would like to insert code that would help him/her to debug his/her code efficiently. A simple example might be inserting a Console.Writeline() call that prints out values or indicates completion (successful or unsuccessful) of the executed part. However, these lines can clutter up the code structure and also needs removal of the debugging code for the release of the entire software.
This overhead is taken care of by specialized methods in C# that help the programmer debug the code without the need to clean up his/her debugging code for the release phase. These methods which are used for debugging are called Conditional methods. The compiler identifies these marked methods and never includes them in the release build.
Well, that’s good enough. But, how do I make a method conditional? .NET provides an attribute System.Diagnostics.ConditionalAttribute (alias Conditional) to achieve this. Let’s look at some code now.
 
Defining the conditional method
public class MyTracer   
{    
    [Conditional("DEBUG")]    
    public static void LogThisMessage(string myMessage, int severity)    
    {    
        //  Write message to screen or a file or ...    
        Console.WriteLine(" DEBUG MESSAGE : " + myMessage +" SEVERITY LEVEL : "+severity);    
    }    
}
 
The Conditional attribute has been applied to the LogThisMessage() method with the DEBUG conditional compilation symbol. This signals the compiler that the method should be ignored if the conditional symbol DEBUG is not specified.
 
Using the conditional method
With the Solution Configurations set to Debug mode if you execute the following code, you would happily see the output window shown below.
 
public static void Main(string[] args)    
{    
    //  Some error occured in my code    
    //  Log the message    
    MyTracer.LogThisMessage("The error 1221 has occured.", 5);    
}

Now lets see what happens to our conditional code in the Release mode. To enable Debug or Release mode you have to look for the Solution Configurations selector in your Visual Studio IDE which is shown below.

Change the mode to “Release” and you would see that the conditional code now has disappeared.
 
We used the predefined DEBUG compilation symbol in our code. You can have your own defined symbols and use them for conditional compilation. You can define custom compilation symbols in Project Properties -> Build tab -> General. Checkboxes have been provided to enable or disable the DEBUG and TRACE symbols.
 
.NET also provides two classes that provide similar functionality:
System.Diagnostics.Debug
System.Diagnostics.Trace
These classes contain methods that can also be used for debugging if you do not need more specific custom methods.

No comments:

Post a Comment