What are obsolete attributes in C#?


If a method has an obsolete attribute, then the compiler issues a warning in the code after it is compiled.

When a new method is being used in a class and if you still want to retain the old method in the class, you may mark it as obsolete by displaying a message the new method should be used, instead of the old method.

The following is an example showing how obsolete attribute is used −

using System;

public class Demo {
   [Obsolete("Old Method shouldn't be used! Use New Method instead", true)]

   static void OldMethod() {
      Console.WriteLine("This is the old method!");
   }

   static void NewMethod() {
      Console.WriteLine("This is the new method!");
   }

   public static void Main() {
      OldMethod();
   }
}

As we have set the warning message above, it will show the following warning −

Compilation failed: 1 error(s), 0 warnings
error CS0619: `Demo.OldMethod()' is obsolete: `Old Method shouldn't be used! Use New Method instead'

Updated on: 20-Jun-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements