The Conditional attribute to control execution of parts of the code in C# .NET

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)

…and the following calling method:

private void RunConditionalExample()
	PrintThis pt = new PrintThis();

The two strings will be printed in the Console window as expected.

Now let’s decorate the Print method as follows:

public class PrintThis
	public void Print(string 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:

Add extra compilation symbol for conditional execution

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.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: