What is Obsolete Keyword?
If we do not want developers to use a certain method then we can declare the method as obsolete. This keyword is used to deprecate a method. One strong reason for doing this could be new version of the method being developed or introduced. Using this keyword we can give a custom message to the user also.
How can I make a method Obsolete?
We can make a method obsolete by putting [Obsolete] attribute on the top of the method. Let us create a program and try to understand more on how to make a method Obsolete in C#.
Write the below code in a console application.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ObsoleteMethod
- {
- class Program
- {
- [Obsolete("This method is Old. Kindly do not use!!")]
- public int AddNumber(int a, int b)
- {
- return a + b;
- }
- public int Add(int a, int b)
- {
- return a + b;
- }
- static void Main(string[] args)
- {
- Program obj = new Program();
- int result = obj.AddNumber(12, 14);
- Console.WriteLine(result);
- Console.ReadLine();
- }
- }
- }

When we try to call the obsolete method we get the same error message defined in the obsolete tag. If we try to run the program it runs and gives us the correct result. Suppose if we want developer to not even use this function then we can use an overloaded version of this keyword by passing a boolean value and setting it to true.
Check the modified version of the code below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ObsoleteMethod
- {
- class Program
- {
- [Obsolete("This method is Old. Kindly do not use!!", true)]
- public int AddNumber(int a, int b)
- {
- return a + b;
- }
- public int Add(int a, int b)
- {
- return a + b;
- }
- static void Main(string[] args)
- {
- Programobj = newProgram();
- int result = obj.AddNumber(12, 14);
- Console.WriteLine(result);
- Console.ReadLine();
- }
- }
- }

Now we are not able to even run the program as we get the run time error. So this is how we can make a method Obsolete in C#.

Mohammad KhalidPosted Apr 12, 2016, 4:11 AM
Well explained....
Rahul ChavanPosted Apr 12, 2016, 3:04 AM
Nice Article Manoj
Manoj KulkarniPosted Apr 11, 2016, 11:11 PM
Nice article. Thank you for sharing