How to mark a method or class as deprecated
As the year 2009 passes away and 2010 countdown have begun let me share with you an important attribute in .net programming world. With new developments in your application it sometime becomes important to mark a method as deprecated or obsolete. Here is the attribute usage to mark the method so.
public class MyClass
{
[Obsolete(“My Reason”, false)]
public void OldMethod()
{
}
public void NewMethod()
{
}
}
Now your “OldMethod” is been marked as obsolete and the compiler would raise as warning when you try to use it. In case you want the compiler to report an error instead of a warning you need to change the 2nd parameter of the obsolete attribute to true.
The “Obsolete” attribute can be used on class.
[Obsolete(“My Reason 2”, false)]
public class MyObsoleteClass
{
public void foo()
{
}
}
Here is detail of the Obsolete class as mentioned in msdn
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event, Inherited = false) ] public class ObsoleteAttribute: Attribute { public ObsoleteAttribute() {...} public ObsoleteAttribute(string message) {...} public ObsoleteAttribute(string message, bool error) {...} public string Message { get {...} } public bool IsError { get {...} } }
Happy programming and a very Happy New Year 2010 !
Nice post.
Just thinking what can be the possible scenarios where the compiler error needs to be forced for a deprecated API.