How to mark a method as Obsolete or Deprecated in C# ?

How can you mark a function or a method as deprecated in c# ? . You can do it in c# using the obsolete attribute .

For Example :

public class Employee
{

        public string Name { get; set; }

        public void SetEmployeeName(string name)
        {
            Name = name;

        }

}

If you need to mark the method SetEmployeeName as deprecated , then , just include the obsolete attrbute before the function like this

public class Employee
{
    public string Name { get; set; }

    [ Obsolete  ]
    public void SetEmployeeName(string name)
    {
        Name = name;

    }

}

When you call the SetEmployeeName , it should only show a warning stating the method is obsolete .

You can add an description for the function too via

    [  Obsolete("SetEmployeeName is deprecated,Use a different method instead", true) ]  ] 
public void SetEmployeeName(string name)
{

    Name = name;

}

The second parameter(true) defines to throw compiler error when this function is called .

Reference

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

3 Responses

  1. Thanks for the post! Very helpful feature for evolving code/API’s that a lot of devs aren’t aware of. The only thing is, it looks like you left off the attribute in question in your second code block.

  2. Pingback: How to mark a method as Obsolete or Deprecated in C# | ProgramInDotnet

Leave a Reply