Export (0) Print
Expand All
6 out of 13 rated this helpful - Rate this topic

Creating Custom Attributes

You can create your own custom attributes by defining an attribute class, a class that derives directly or indirectly from System.Attribute (which makes identifying attribute definitions in metadata fast and easy). Suppose you want to tag classes and structs with the name of the programmer who wrote the class or struct. You might define a custom Author attribute class:

using System;
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)]
public class Author : Attribute
{
   public Author(string name) { this.name = name; version = 1.0; }
   public double version;
   string name;
}

The class name is the attribute's name, Author. It is derived from System.Attribute, so it is a custom attribute class. The constructor's parameters are the custom attribute's positional parameters (in this case, name), and any public read-write fields or properties are named parameters (in this case, version is the only named parameter). Note the use of the AttributeUsage attribute to make the Author attribute valid only on class and struct declarations.

You could use this new attribute as follows:

[Author("H. Ackerman", version=1.1)] class SomeClass{...}

AttributeUsage has a named parameter, AllowMultiple, with which you can make a custom attribute single-use or multiuse.

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,
   AllowMultiple=true)] // multiuse attribute
public class Author : Attribute
{
   ...
}

See Also

Introduction to Attributes | Using Attributes | Attribute Targets | Global Attributes | Retrieving Attribute Information | AttributeUsage

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.