Articles → .NET → Conditional attribute in C#

Conditional attribute in C#






What is conditional attribute?





Syntax


[Conditional("symbol_name")]





Example






//  During development time
#define debug
using System;
using System.Diagnostics;

namespace Test {
  class Program {
    static void Main(string[] args) {
      Program p = new Program();
      p.ExecuteLogic1();
      p.LogMessage("Test Message");
      p.ExecuteLogic2();
      Console.ReadLine();
    } 
    [Conditional("debug")]
    public void LogMessage(string message) {
      Console.WriteLine(message);
    }

    public void ExecuteLogic1() {
      Console.WriteLine("Logic 1");
    }
    public void ExecuteLogic2() {
      Console.WriteLine("Logic 2");
    }
  }
}




Picture showing the code with the conditional attribute while running in development mode

Click to Enlarge





//  During production deployment time
//#define debug
using System;
using System.Diagnostics;

namespace Test {
  class Program {
    static void Main(string[] args) {
      Program p = new Program();
      p.ExecuteLogic1();
      p.LogMessage("Test Message");
      p.ExecuteLogic2();
      Console.ReadLine();
    } 
    [Conditional("debug")]
    public void LogMessage(string message) {
      Console.WriteLine(message);
    }

    public void ExecuteLogic1() {
      Console.WriteLine("Logic 1");
    }
    public void ExecuteLogic2() {
      Console.WriteLine("Logic 2");
    }
  }
}




Picture showing the code with the conditional attribute while running in production mode

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, May 27, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250