Under what condition I should make a method obsolete, that is the question in your mind, isn’t it?
Here we goes, suppose you work with bigger application with lots of developers involved in, and the team want to make some serious change to the API or some of the methods, which is already used by others. All you need to make the old method obsolete and tell fellow developers to use the new one. This can be done with property of C# class.
A property cam placed inside a set of square brackets just below the method that is deprecated as follows.
{
class Program
{
static void Main(string[] args)
{
DisplayString(“Welcome”);
Console.ReadKey();
}
[Obsolete]
static void DisplayString(string st)
{
Console.Write(st);
}
static void DisplayStringNew(string st)
{
Console.Write(“\nMessage: ” + st);
}
}
}
The second constructor allow us to pass a message for indicating the new method you just added, and the third constructor will make the usage of obsoleted methods caused for compile error, if it set true. (this is the best way to force other programmers to use the new DisplaySretingNew method).
Lets rewrite the above code with third constructor and it will put red line under the old method call. Just point the error line and it will show the following message.
{
class Program
{
static void Main(string[] args)
{
DisplayString(“Welcome”);
Console.ReadKey();
}
[Obsolete(“Use DisplayStringNew”,true)]
static void DisplayString(string st)
{
Console.Write(st);
}
static void DisplayStringNew(string st)
{
Console.Write(“\nMessage: ” + st);
}
}
}
Download source code
Requirements: VS 2012/2015
More property magic will coming soon.