Skip to main content

The basics of .NET attributes

April 19, 2012 mgroves 0 Comments
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:

Comments

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter