Yogesh Jagota's Personal Blog
small c# code snippets and free code libraries

Method level #if #endif of C#: Conditional attribute

Saturday, 1 March 2008 18:34 by Yogesh Jagota

#if and #endif directives are a common practise used by many programmers to compile code conditionally based on environmental variables. Another way is to use the Conditional attribute defined in System.Diagnostics. 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.

Usage:

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          int i = 0;
   6:  
   7:          DebugMethod(ref i);
   8:  
   9:          i++;
  10:  
  11:          Console.WriteLine(i.ToString());
  12:      }
  13:  
  14:      [Conditional("DEBUG")]
  15:      static void DebugMethod(ref int i)
  16:      {
  17:          i++;
  18:      }
  19:  }


Conditional attribute's constructor takes one string parameter which defines the environmental variable to check. You can define environmental variables in Project Properties >> Build. DEBUG is already defined in debug configuration, and TRACE is always defined regardless of any configuration.

One important thing to note is that the method which is marked using the Conditional attribute must have a return type of void otherwise the code will not compile.

In the above example, if DEBUG is defined, the example will print 2, otherwise 1.

Actually, the above example is more or less equal to the following snippet with #if and #endif:

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          int i = 0;
   6:  
   7:          DebugMethod(ref i);
   8:  
   9:          i++;
  10:  
  11:          Console.WriteLine(i.ToString());
  12:      }
  13:  
  14:      static void DebugMethod(ref int i)
  15:      {
  16:          #if DEBUG
  17:          i++;
  18:          #endif
  19:      }
  20:  }


but in reality, the compiler removes all the instances where DebugMethod is called if DEBUG environmental variable is not defined. So the actual IL is equal to:

   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          int i = 0;
   6:  
   7:          i++;
   8:  
   9:          Console.WriteLine(i.ToString());
  10:      } 
  11:      [Conditional("DEBUG")]
  12:      static void DebugMethod(ref int i)
  13:      {
  14:          i++;
  15:      }
  16:  }

Note that the method is still compiled regardless of whether DEBUG is defined or not.

You can apply the attribute as many times as you want to a single method, like:

   1:  [Conditional("DEBUG"), Conditional("TRACE")]
Del.icio.usDigg It!DZone It!kick it on DotNetKicks.com
Tags:  
Categories:   C#
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Add comment


 

biuquote
Loading