Marking Code as Deprecated in .NET

Do you work on a team that shares code libraries? Have you ever wanted to implement a new method to replace an old one (with a differing signature) and simply deleted the old method? You can handle these situations easier by using an attribute on a class or method. The attribute is called Obsolete. This allows you to gracefully mark code as deprecated as shown below:

C#

   1: [Obsolete("This class has been deprecated.")]
   2: public class Test
   3: {
   4:     [Obsolete("This method has been deprecated.")]
   5:     public void FooBar () { }
   6: }

VB

   1: <Obsolete("This class has been deprecated.")>
   2: Public Class Test
   3:     <Obsolete("This method has been deprecated.")>
   4:     Public Sub FooBar()
   5:     End Sub 
   6: End Class

However, in the code above, both of these instances will only show a warning in the compiler. To throw an exception, you can add another property to the code to pass in a Boolean value to throw an exception as shown below:

C#

   1: [Obsolete("This class has been deprecated.", true)]
   2: public class Test
   3: {
   4:     [Obsolete("This method has been deprecated.", true)]
   5:     public void FooBar () { }
   6: }

VB

   1: <Obsolete("This class has been deprecated.", True)>
   2: Public Class Test
   3:     <Obsolete("This method has been deprecated.", True)>
   4:     Public Sub FooBar()
   5:     End Sub 
   6: End Class


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>