Declaring Obsolete Methods in your C# and VB.NET Classes

When building class libraries, it is important to let developers know when a piece of functionality is considered obsolete. In .Net this is possible by decorating a method or a property with the Obsolete attribute. By using this attribute you can display a message to the developer when they use this informing them this is an obsolete function, or even throw an error preventing them from using the function.

In the below example, a method is decorated with the attribute but the user can still compile the application:

C#

public class OldMethods
{
[Obsolete("This method will be removed from future versions")]
public void MyOldMethod()
{
}

public void MyNewMethod()
{

}
}

VB.NET

Public Class OldMethods
<Obsolete("This method will be removed from future versions")> _
Public Sub MyOldMethod()
End Sub

Public Sub
MyNewMethod()

End Sub
End Class

The developer will see a nicely formatted message when using this function:

clip_image002

You can also prevent code from being compiled if the developer uses the old method by adding a boolean value after the message:

C#

public class OldMethods
{
[Obsolete("This method will be removed from future versions", true)]
public void MyOldMethod()
{
}

public void MyNewMethod()
{
}
}

VB.NET

Public Class OldMethods
<Obsolete("This method will be removed from future versions", True)> _
Public Sub MyOldMethod()
End Sub

Public Sub
MyNewMethod()
End Sub
End Class


Now when the developer tries to compile their code they will see a compilation error:

clip_image002[5]






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

2 comments:

James Curran said...

>> [Obsolete("This method will be removed from future versions")]

Please, please, please... Do not follow this example of an Obsolete message.

A proper Obsolete message:

[Obsolete("This method will be removed from future versions. Use MyNewMethod instead.")]

PHenry said...

I keep forgetting which attribute to use to obsolete an api call. Very cool and thanks for the overloaded information!