The basics of .NET attributes

Posted by mgroves on April 19, 2012  •  Comments (0)  •  Tags: .NET, attributes

Attributes in .NET are classes that derive from the Attribute class. Here's an example of an attribute as seen in ASP.NET MVC:

Attributes themselves don't actually do anything: they are strictly meta data. It's up to a framework or tool (ASP.NET MVC, WCF, PostSharp, to name a few) to interpret and use any code in or to infer any meaning from those attributes.

Attributes can have contructors, and you can use those constructors when putting an attribute on a class. But you can only use constant values (like a string literal, an integer literal, an enum literal).

You also can't use type parameters on an attribute, but you can use typeof() when using an attribute.

As I stated above, attributes don't actually do anything on their own. To see what attributes are applied, use Reflection. For instance, to get attributes set on a class:

Leave a Comment

* = Required
*
*

Some HTML will be escaped, you can use StackOverflow-flavored Markdown