How to make method obsolete in c#.Net


C# has packed magical feature like ‘property, which can be used in a variety of ways. We will start with a console application with two methods and going to make one of them obsolete.

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.

namespace ConsoleApplication1
{
    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);
        }
    }
}

This will place an warning message for the method that is deprecated. C# has a special class for Obsolete actions, which come with three constructor, the default one and with arguments.

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.

namespace ConsoleApplication1
{
    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.