So its pretty much common practise for many to use #if and #endif directives to create different builds in your application while using the same source. In a previous tutorial I displayed how you can use the #if directive to force your methods to not ASP.NET caching during debug mode (ASP.NET Caching Techniques).
The #if #endif directives can be useful at times can make source code hard to read. As an alternative one could use the C# conditional attribute.
The C# conditional attribute basically allows you to control when a method should and should not be called. The benefit of the C# conditional attribute is that it is applied at the method level, which results in source code that is more readable.
To show you an example of the conditional attribute, let's use it to output debugging statements. We're going to create a method that displays debugging information and then were going to add this method to a classes. Note that this debugging method will only be a part or classes when they have set a particular environmental variable.
So our debugging method that will look something like this:
[ Conditional("Debug") ]
public void DebugThis()
{
// get the name of the calling routine using Reflection
//
string _callingMethod = new StackTrace().GetFrame(1).GetMethod().Name;
Trace.WriteLine("Entering DebugThis called by:" + _callingMethod);
// insert other checks here like Asserts etc.
//
Trace.WriteLine("Exiting DebugThis for " + _callingMethod);
}
So the method above marked with the
conditional attribute will be called in all of our properties.
public string UserName
{
get
{
DebugThis();
return _userName;
}
}
So, the method DebugThis() has been marked to be used only during debug mode. The conditional attribute tells the compiler that when the debug environmental variable is used, and then and only then do we call the DebugThis method. So if the DEBUG environmental airboat is not defined, the property UserName will look like:
public string UserName
{
get
{
return _userName;
}
}
Please note that regardless of the
debug environment variable i.e. if it defined or not, the DEBUG this method will be compiled into your assembly. But keep in mind that when the debug environmental airboat is not defined, the debug method will be in the assembly. But it does not get loaded into memory, nor is it JITed unless it is called.
You can also use other predefined symbols like Conditional("Trace") or even combine more than one like:
[Conditional("DEBUG"), Conditional("TRACE")]
Or even create your own symbols and use them.
So in summary, the Conditional Attribute enables developers to better separate conditional code when compared to the #if directives and it also how to structure your code more cleanly.