How to indicate that code is obsolete in C# .NET

Say you have a class or a class member that you’d like to remove at a later stage. You’ve probably seen compiler warnings or even errors with a message like “abc.efg is obsolete: ‘some message'”.

Let’s see quickly how to achieve it in C#.

The attribute to be aware of is Obsolete. It can decorate both classes, properties and methods. You can attach a useful message to it and make the compiler issue an error instead of the default warning. Let’s see an example:

[Obsolete]
public class CurrentCustomer
{
	public void Buy()
	{
	}
}

If you have this class in your project and compile it then at first you won’t see any warning unless the class is referenced somewhere. As soon as the class is referenced…

CurrentCustomer customer = new CurrentCustomer();

…then you’ll see a warning – actually 2 as there are 2 references to this object:

Default obsolete warnings on class level

Simply showing this message won’t help the callers too much so let’s add a message:

[Obsolete("Don't use this class in the future. It will be replaced by NewCustomer.")]
public class CurrentCustomer
{
	public void Buy()
	{
	}
}

Compile the project and you’ll see the message in the list of warnings.

You can apply the attribute to a method:

public class CurrentCustomer
{
	[Obsolete("Don't use this method in the future. It will be replaced by the BuyWith method.")]
	public void Buy()
	{
	}
}

As soon as the method is referenced…

CurrentCustomer customer = new CurrentCustomer();
customer.Buy();

…we’ll get the warning:

Obsolete method warning

In case you want the compiler to issue an error instead then you can use another overload of the attribute:

public class CurrentCustomer
{
	[Obsolete("Don't use this method in the future. It will be replaced by the BuyWith method.", true)]
	public void Buy()
	{
	}
}

…and here’s the error:

Compiler error when obsolete is applied

View all various C# language feature related posts here.

Advertisement

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

One Response to How to indicate that code is obsolete in C# .NET

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 )

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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: