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:

class MyClass
{
[Obsolete]
public void SaySomething(){}
}

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.

class MyClass
{
[Obsolete("Use method SaySomething1")]
public void SaySomething(){ Console.WriteLine("Execute saysomething()");}
public void SaySomething1(){ Console.WriteLine("Execute saysomething1()");}
}

code

If you want to show an error when calling the method SaySomething() then you must pass another overloaded version.

class MyClass
{
[Obsolete("Use method SaySomething1",true)]
public void SaySomething(){ Console.WriteLine("Execute saysomething()");}
public void SaySomething1(){ Console.WriteLine("Execute saysomething1()");}
}

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.

Tags: , ,