Working With C# Custom Attributes C# gives us a new, flexible solution to associate information with some class, named attributes. For example: [Serializable] class Max { public int x,y; } Here the attribute informs us that, Class "Max" may be serialized in some point of time. Such additional information about our class may help us remember, What is this class all about? But, .NET says more: attributes can be queried at runtime! How does .NET do it? At first, we must understand, that attributes are simply classes that derives from System.Attribute. So, for defining new attribute we must write a class. Let's look an example - Meou attribute for cat Classes describes why some kind of cats says "Meou". public class MeouAttribute : Attribute { public string Why; public MeouAttribute(string Why) { this.Why=Why; } } By writing those lines we have defined custom attribute! Let's use it: [Meou("No reason")] // normal cats say meou without reason public class Cat { } [Meou("I'm hungry")]// hungry cats meou public class HungryCat : Cat { } [Meou("Want to be patted..")]// pussy cat public class PussyCat : Cat {
Working With C# Custom Attributes } Okay,So nice. But what we can do with this attributes? .NET gives us a new weapon: Runtime querying of these attributes. How? Let's write little function receives a type of cat and determines, why it "Meou"d. public string WhyISaidMeou(Cat cat) { Type type=cat.GetType();// Get object type object obj=type.GetCustomAttributes()[0];// Get first attribute if(obj is MeouAttribute)// If it's of Type Meou return ((MeouAttribute)obj).Why; else // other attribute return "First attribute is not Meou!"; } Simple? Yes! Now use it: Cat cat1=new Cat(); Cat cat2=new HungryCat(); Cat cat3=new PussyCat(); string why1,why2,why3; why1=WhyISaidMeou(cat1);// receives "No reason" why2=WhyISaidMeou(cat2);// "hungry" why3=WhyISaidMeou(cat3);// " Want to be patted " Application.Exit();