C# attributes

Attributes are tags declaring the behavior of the modified element. The builtin Attributes include Obsolete and Conditional.

public class B
{
[System.Obsolete("The Add method is obsolete, use Sum instead", true)]
public int Add(int x, int y)
{
return x + y;
}
public int sum(int x, int y)
{
return (x * 2) + y;
}
}
B obj = new B();
int ori = obj.Add(3,4); //compile error, The Add method is obsolete, use Sum instead
int ori = obj.Sum(3,4); //10

If the 2nd parameter of Obsolete is false (by default), then the modified method will not cause compile error.
public class B
{
[System.Obsolete("The Add method is obsolete, use Sum instead", false)]
public int Add(int x, int y)
{
return x + y;
}
public int sum(int x, int y)
{
return (x * 2) + y;
}
}
B obj = new B();
int ori = obj.Add(3,4); //OK, with a warning, ori=7
int ori = obj.Sum(3,4); //10

Using Attributes to modify class.
[System.Obsolete("The class is obsolete",true)]
public class B
{
...
}
B obj = new B(); //compile error, The class is obsolete


endmemo.com © 2024  | Terms of Use | Privacy | Home