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]

2 comments:

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

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

    ReplyDelete