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)
	{
		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:

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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: