This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Marking C# Code As Obsolete

As class libraries evolve over time, new functionality will be added and existing classes, methods and properties will be improved. Sometimes this means that older code is superseded and it is preferable that it is marked as obsolete and no longer used.

Obsolete Attribute

The Obsolete attribute may be added to classes or class members to indicate that they have been superseded. Depending upon the usage of the attribute, a warning message can be provided to users of the class or member. The message can be displayed as either a warning or as a compiler error when a user of the class library accesses the outdated definition. The message is displayed whenever a deprecated class is used or inherited from or when an out-of-date member is accessed.

Basic Usage

The simplest use of the Obsolete attribute is with no parameters specified. To apply the attribute, [Obsolete()] is used to decorate the class or member being deprecated. On compilation of a program that uses the item, a warning that it is obsolete is issued.

public class OutOfDateClass
{ ... }

Warning Message

To improve the readability of a compiler warning, a message can be added as a string parameter of the attribute. This is displayed alongside the obsolete item warning when code that uses the class or member is compiled.

[Obsolete("This method has been superseded by the IsInUse() method")]
public void NotInUse()
{ ... }

Error Message

Finally, if using the deprecated version of the code is no longer supported at all or causes problems that are unacceptable, the attribute can be flagged with a Boolean that indicates that this is an error rather than a warning. In this case, code that uses a deprecated method cannot even be compiled.

[Obsolete("This method has been superseded by the IsInUse() method", true)]
public void NotInUse()
{ ... }
23 October 2007