How to make a method deprecated in C#?


The Obsolete Attribute marks elements like classes, methods, properties, fields, delegates, and many others within our code as deprecated or obsolete. The attribute is read at compile time and it is used to generate a warning or an error to the developer.

This attribute can help if we have ever wanted to make sure programmers use newer versions of methods. It also makes it easier when we are transitioning from older methods to newer ones. Marking an item as obsolete warns users that program elements will be removed in future versions of the code base.

This attribute is found in the System namespace. The Obsolete attribute decorates a program element by putting the word “Obsolete” above it inside square brackets. Since it is an attribute, we can use either Obsolete or ObsoleteAttribute.

Obsolete attribute has three constructors −

  • [Obsolete] − is a no parameter constructor and is a default using this attribute.

  • [Obsolete(string message)] − in this format we get message of why this method is deprecated.

  • [Obsolete(string message, bool error)] − in this format along with the message we can control whether the complier should throw error during the compilation time.

Example

using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         ObseleteMethod();
         ObseleteMethodWithMessage();
         ObseleteMethodWithMessageAndNoFail();
         ObseleteMethodWithMessageAndFail();
      }
      [Obsolete]
      public static void ObseleteMethod() { }
      [Obsolete("This Method is Deprecated")]
      public static void ObseleteMethodWithMessage() { }
      [Obsolete("This Method is Deprecated", false)]
      public static void ObseleteMethodWithMessageAndNoFail() { }
      [Obsolete("This Method is Deprecated", true)]
      public static void ObseleteMethodWithMessageAndFail() { }
   }
}

Output

The output of the above code is

 

Updated on: 04-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements