How to use obsolete attribute in C# code

Description

The Obsolete attribute is short for System.ObsoleteAttribute, which lets you mark a program element as obsolete.

It has this general form:

[Obsolete("message")]

A second form of Obsolete is shown here:

[Obsolete("message", error)]

error is a Boolean value.

If error is true, then the obsolete item generates a compilation error rather than a warning.

Example 1


using System; //  w  w  w .ja  va 2s .  com
 
class MainClass { 
 
  [Obsolete("Use myMeth2, instead.")]  
  static int myMethod(int a, int b) { 
    return 0; 
  } 
 
  // Improved version of myMethod. 
  static int myMethod2(int a, int b) { 
    return 1; 
  } 
 
  public static void Main() { 
   // warning displayed for this 
    Console.WriteLine("4 / 3 is " + myMethod(4, 3)); 
 
   // no warning here 
    Console.WriteLine("4 / 3 is " + myMethod2(4, 3));  
  } 
}

The code above generates the following result.

Example 2

Obsolete attribute: warn the user that Method is obsolete.


using System;//ww w.  jav  a  2 s. c o m

class MainClass
{
  [Obsolete("Method1 has been replaced by NewMethod1", false)]
  public static int Method1()
  {
    return 1;
  }

  public static void Main() 
  {

    Console.WriteLine(Method1());
  }

}

The code above generates the following result.

Example 3

The following code uses true value for the second parameter which tells the runtime to throw an error if the user tries to use Method2.


using System;//from  w w  w .java  2s .  c  om

class MainClass
{
  
  [Obsolete("Method2 has been replaced by NewMethod2", true)]
  public static int Method2()
  {
    return 2;
  }

  public static void Main() 
  {
    Console.WriteLine(Method2());
  }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor