Obsolete Attribute in C#

Problem

Suppose I made a class named MyClass having the method SaySomething() and you implemented this class and the method in the entire project. Then the requirement comes that there is no need to implement the class MyClass or the method called SaySomething. But you need to implement a method called SaySomething1(). In this scenario we use the Obsolete attribute.

Solution


We can do this using the Obsolete attribute as in the following:

  1. class MyClass  
  2. {  
  3.       [Obsolete]  
  4.       public void SaySomething(){}  
  5. }  
console application

When you compile the project it will generate a warning but the method SaySomething will be executed. But there is the problem of how does the developer know which method will be called instead of SaySomething(). In this scenario we implement an overloaded version of Obsolete attribute.

If you want to show the warning as a message then you need to pass a parameter.
  1. class MyClass  
  2. {  
  3.       [Obsolete("Use method SaySomething1")]  
  4.       public void SaySomething(){ Console.WriteLine("Execute saysomething()");}  
  5.       public void SaySomething1(){ Console.WriteLine("Execute saysomething1()");}  
  6. }  
code

If you want to show an error when calling the method SaySomething() then you must pass another overloaded version.
  1. class MyClass  
  2. {  
  3.       [Obsolete("Use method SaySomething1",true)]  
  4.       public void SaySomething(){ Console.WriteLine("Execute saysomething()");}  
  5.       public void SaySomething1(){ Console.WriteLine("Execute saysomething1()");}  
  6. }  
error list

After implementation of Obsolete calling the SaySomething1 method it's generating the output as we expected.

c sharp code

Note: We can implement Obsolete on the class as well.

 


Similar Articles