See Also: Attribute Members
All attributes, whether built-in or user-defined, derive directly or indirectly from Attribute. Attributes inherit certain default behaviors: the attribute might be associated with any target element (see AttributeTargets); might or might not be inherited by a derived element; and multiple instances might or might not be allowed on the same target element. These behaviors are specified using AttributeUsageAttribute.
The CLI predefines some attribute types and uses them to control runtime behavior. Some languages predefine attribute types to represent language features not directly represented in the Common Language Specification (CLS). User-defined attribute classes, inheriting from Attribute, can also be created. The definition of such a class includes the name of the attribute, its default behavior, and the information to be stored.
The following example creates and assigns multiple custom attributes to a class. The attribute contains the name of the programmer and the version number of the class.
C# Example
using System;
[AttributeUsage(AttributeTargets.Class|
AttributeTargets.Struct,
AllowMultiple=true)]
public class Author : Attribute
{
string authorName;
public double verSion;
public Author(string name)
{
authorName = name;
verSion = 1.0;
}
public string getName()
{
return authorName;
}
}
[Author("Some Author")]
class FirstClass
{
/*...*/
}
class SecondClass // no Author attribute
{
/*...*/
}
[Author("Some Author"),
Author("Some Other Author", verSion=1.1)]
class ThirdClass
{
/*...*/
}
class AuthorInfo
{
public static void Main()
{
PrintAuthorInfo(typeof(FirstClass));
PrintAuthorInfo(typeof(SecondClass));
PrintAuthorInfo(typeof(ThirdClass));
}
public static void PrintAuthorInfo(Type type)
{
Console.WriteLine("Author information for {0}",
type);
Attribute[] attributeArray =
Attribute.GetCustomAttributes(type);
foreach(Attribute attrib in attributeArray)
{
if (attrib is Author)
{
Author author = (Author)attrib;
Console.WriteLine(" {0}, version {1:f}",
author.getName(),
author.verSion);
}
}
Console.WriteLine();
}
}
The output is
Author information for FirstClass