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]



Will you give this article a +1 ? Thanks in advance




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

comments

2 Responses to "Declaring Obsolete Methods in your C# and VB.NET Classes"
  1. James Curran said...
    September 9, 2009 at 8:48 AM

    >> [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.")]

  2. PHenry said...
    September 9, 2009 at 10:19 AM

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

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions