How to indicate that code is obsolete in C# .NET
February 27, 2015 1 Comment
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:
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:
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:
View all various C# language feature related posts here.
Reblogged this on Dinesh Ram Kali..