Wednesday, March 24, 2010

Combining Attributes

Attributes can be grouped or combined. For example, we can group the two attributes Obsolete and Conditional as shown in this example:
[Obsolete]
[Conditional (“TRACE”)]
We can also combine the attributes by listing them inside a pair of square brackets and separating them with commas:
[Obsolete, Conditional (“TRACE”)]
We can also combine the two styles together as shown in this example, which used three attributes:
[Serializable]
[Obsolete, Conditional (“TRACE”)]
The following example demonstrates combining attributes.
//Attribute example
#define TRACE
using System;
using System.Diagnostics;
public class MyClass
{
    [Obsolete(“Please use MyNewMethod.”, false)]
    [Conditional(“TRACE”)]
    public void MyMethod(string s)
    {
        Console.WriteLine(s);
    }
    static void Main()
    {
        MyClass mc = new MyClass();
        mc.MyMethod(“The conditional method is executed.”);
        Console.WriteLine(“End execution.”);
    }
}

No comments:

Post a Comment