C# Tips & Tricks #35 – Mark method as Obsolete or Deprecated

This blog post will explain in simple steps on how you can mark a method or function obsolete in C# or “deprecated” in C# using the Obsolete keyword.

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

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 .

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

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 .

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

    2 Comments

  1. Mike
    February 7, 2011
    Reply

    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. February 7, 2011
    Reply

    Ah ,

    Thanks Mike for letting me updated on this …

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...