The fact that you can define custom attributes and place them in your source code would be of little value without some way of retrieving that information and acting on it. Fortunately, C# has a reflection system that allows you to do just that. The key method is GetCustomAttributes, which returns an array of objects that are the run-time equivalents of the source code attributes.
An attribute specification such as
[Author("H. Ackerman", version=1.1)] class AClass {...}
is conceptually equivalent to this:
Author anonymousAuthorObject = new Author("H. Ackerman"); anonymousAuthorObject.version = 1.1;
However, the code is not executed until AClass
is queried for attributes. Calling GetCustomAttributes on AClass
causes an Author object to be constructed and initialized as above. If the class has other attributes, other attribute objects are constructed similarly. GetCustomAttributes then returns the Author object and any other attribute objects in an array. You can then iterate over this array, determine what attributes were applied based on the type of each array element, and extract information from the attribute objects.
Here is a complete example. A custom attribute is defined, applied to several entities, and retrieved via reflection.
using System; [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct, AllowMultiple=true)] public class Author : Attribute { public Author(string name) { this.name = name; version = 1.0; } public double version; string name; public string GetName() { return name; } } [Author("H. Ackerman")] class FirstClass { /*...*/ } class SecondClass { /*...*/ } // no Author attribute [Author("H. Ackerman"), Author("M. Knott", version=1.1)] class Steerage { /*...*/ } class AuthorInfo { public static void Main() { PrintAuthorInfo(typeof(FirstClass)); PrintAuthorInfo(typeof(SecondClass)); PrintAuthorInfo(typeof(Steerage)); } public static void PrintAuthorInfo(Type t) { Console.WriteLine("Author information for {0}", t); object[] attrs = t.GetCustomAttributes(); for (int i=0; i<attrs.Length; ++i) { if (attrs[i] is Author) { Author a = (Author)attrs[i]; Console.WriteLine(" {0}, version {1:f}", a.GetName(), a.version); } } } }
Author information for FirstClass H. Ackerman, version 1.00 Author information for SecondClass Author information for Steerage H. Ackerman, version 1.00 M. Knott, version 1.10
Introduction to Attributes | Using Attributes | Global Attributes | Creating Custom Attributes