The Conditional attribute to control execution of parts of the code in C# .NET
March 10, 2015 Leave a comment
In this post we saw how to use the #if preprocessor to control the execution of code. The compiler will understand those instructions and compile away bits of code.
There’s another way to achieve something similar using the Conditional attribute. You can decorate methods with this attribute. It accepts a string parameter which defines the name of the symbol that must be defined in order for the method to be carried out.
Consider the following class:
public class PrintThis { public void Print(string what) { Console.WriteLine(what); } }
…and the following calling method:
private void RunConditionalExample() { PrintThis pt = new PrintThis(); pt.Print("Hello"); pt.Print("Goodbye"); }
The two strings will be printed in the Console window as expected.
Now let’s decorate the Print method as follows:
public class PrintThis { [Conditional("PRINT")] public void Print(string what) { Console.WriteLine(what); } }
Rerun the code and you’ll see that the Print method wasn’t called. Why? Because the PRINT compilation symbol is not defined. You can add extra symbols in the project properties:
As soon as PRINT is added and you rerun the code then the Print method will be executed. If PRINT is not defined then the compiler will compile away all calls to the methods referenced by the symbol as if they are not there in your code.
View all various C# language feature related posts here.