C# Obsolete Attribute
In this chapter you will learn:
- How to use obsolete attribute
- Example for obsolete attribute
- Obsolete attribute with error message and compiler error
- Generate a compilation error rather than a warning
Description
The Obsolete attribute is short for System.ObsoleteAttribute, which lets you mark a program element as obsolete.
It has this general form:
[Obsolete("message")]
A second form of Obsolete is shown here:
[Obsolete("message", error)]
error
is a Boolean value.
If error is true, then the obsolete item generates a compilation error rather than a warning.
Example 1
using System; //from w w w. j a v a 2 s .c om
class MainClass {
[Obsolete("Use myMeth2, instead.")]
static int myMethod(int a, int b) {
return 0;
}
// Improved version of myMethod.
static int myMethod2(int a, int b) {
return 1;
}
public static void Main() {
// warning displayed for this
Console.WriteLine("4 / 3 is " + myMethod(4, 3));
// no warning here
Console.WriteLine("4 / 3 is " + myMethod2(4, 3));
}
}
The code above generates the following result.
Example 2
Obsolete attribute: warn the user that Method is obsolete.
using System;/* ww w . ja v a 2 s.c om*/
class MainClass
{
[Obsolete("Method1 has been replaced by NewMethod1", false)]
public static int Method1()
{
return 1;
}
public static void Main()
{
Console.WriteLine(Method1());
}
}
The code above generates the following result.
Example 3
The following code uses true value for the second parameter which tells the runtime to throw an error if the user tries to use Method2.
using System;/*from www . j av a 2 s. c o m*/
class MainClass
{
[Obsolete("Method2 has been replaced by NewMethod2", true)]
public static int Method2()
{
return 2;
}
public static void Main()
{
Console.WriteLine(Method2());
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to use conditional attribute
- Example for C# Conditional Attribute
- Conditional attribute setting in Compile parameter