Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attributes and their uses

Tags:

I really don't know much about attributes in general in C#, I've seen them in use in a lot of different ways/places but I don't think I see the importance of some of them. Some definitely have importance because they provide a noticeable function, such as [Serializable]. Yet, others don't seem so important, such as one my coworker uses to mark properties with [DataMember].

I suppose my question is, what are attributes and how are they useful? Is there a way to create my own attributes and how can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?

like image 643
Corey Ogburn Avatar asked Jul 07 '10 17:07

Corey Ogburn


1 Answers

what are attributes?

Attributes enable you to embed information about a type or method in the metadata which describes that type or method.

You typically want to use attributes to describe facts about the mechanism of the type or method rather than the meaning of the type or method. For example, suppose you have a type Employee. A fact about the meaning of Employee is that it is a kind of Person, that an Employee has a Manager, and so on. A fact about the mechanism of Employee is that it can be the target of data binding, or it can be serialized to disk, or whatever. An employee cannot be serialized to disk, but the class Employee can be. Attributes let you separate information about the technical details from the semantic model.

Is there a way to create my own attributes?

Yes. Create a class which extends Attribute. By convention you want to name it "FooAttribute". If you do so you can use either the [Foo] syntax or the [FooAttribute] syntax at your discretion.

How can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?

Use the GetCustomAttributes method on the reflection objects.

Where should I read for more information?

Start with the attributes tutorial:

http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx

And then read all of chapter 17 of the C# specification.

like image 112
Eric Lippert Avatar answered Oct 13 '22 00:10

Eric Lippert