Thursday, April 16, 2009

CONDITIONAL ATTRIBUTE

In c# you may need methods which will run when in curtain situations(not like if like when you are testing or in debug mode or in release mode) we use a conditional attribute for this situations.Maybe you have an opening screen  in your application and like me you hate losing time,

   1: using System;
   2: using System.Text;
   3: using System.Diagnostics;
   4:  
   5: namespace Master
   6: {
   7:     class Program
   8:     {
   9:         static void Main(string[] args)
  10:         {
  11:             Test t = new Test();
  12:             t.TestA();
  13:             t.TestB();
  14:             t.TestC();
  15:             Console.Read();
  16:         }
  17:     }
  18:      class Test
  19:     {
  20:          public void TestA()
  21:          {
  22:              Console.WriteLine("AAAAA");
  23:          }
  24:          [Conditional("DEBUG")]
  25:          public void TestB()
  26:          {
  27:              Console.WriteLine("BBBBB");
  28:          }
  29:          [Conditional("TEST")]
  30:          public void TestC()
  31:          {
  32:              Console.WriteLine("CCCCC");
  33:          }
  34:  
  35:     }
  36: }

In this example  TestA method will always work if you are in debug mode TestB will run and if you add “TEST” to conditional compilation symbols TestC will run.

No comments: