C# - How to Create an Obsolete Method in a Class?

Here, we are going to learn how to create an obsolete method in a class using C# program?
Submitted by Nidhi, on September 10, 2020 [Last updated : March 22, 2023]

To create an obsolete method, we need to use the Obsolete attribute to generate a compile-time warning.

C# program to create an obsolete method in a class

The source code to create an obsolete method in a C# class is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - How to Create an Obsolete Method in a Class?
using System;

class Sample
{
    [Obsolete("Use Display() method")]
    static void Print()
    {
    }
    
    static void Display()
    {
        Console.WriteLine("Print() method is obsolete, Use Display method in place of Print() method");
    }

    static void Main()
    {
        Print();
        Display();
    }
}

Output

Print() method is obsolete, Use Display method in place of Print() method
Press any key to continue . . .

Explanation

In the above program, we created a Sample class that contains three methods Print(), Display(), and Main().

Here we used the Obsolete attribute to obsolete a method with a specified warning message. Then we called both Print() and Display() method in the Main() method.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.