Jimmy Hoffa
Jimmy Hoffa

Reputation: 5967

What's the simplest most elegant way to utilize a custom attribute

So a little confession, I've never written an attribute class. I understand they serve the purpose of decorating classes with flags or extra functionality possibly.

Can someone give me a quick example of not just creating and applying an attribute to a class, but rather utilizing the attribute from another block of code. The only code samples I've ever seen to utilize any form of attributes was doing so with reflection, though I've always hoped there's a way of using them without reflection.

Upvotes: 6

Views: 3350

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 660024

The simplest and most elegant way to use an attribute from another block of code is to use a property instead of an attribute.

See Link for a discussion of the differences between properties and attributes.

Upvotes: 6

Andreas
Andreas

Reputation: 1311

First create your attribute

public class ImportableAttribute : Attribute
{

}

Then a class with a item that uses the Attribute

[ImportableAttribute]
public class ImportClass
{
    [ImportableAttribute]
    public string Item {get; set;}
}

Then check if that property uses that attribute. Can be done with classes to.. Of course :)

PropertyInfo property = typeof(ImportClass).GetProperty("Item");

if (property.IsDefined(typeof(ImportableAttribute),true))
{
     // do something
}

With a class:

typeof(ImportClass).IsDefined(typeof(ImportableAttribute), true);

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

Attributes are always used with reflection. They are baked into the metadata of the types during compile time and the only way to read them is through reflection. Attributes are used when you want write a type and you want to associate some metadata with it which could be used by consumers of this type.

Upvotes: 12

Related Questions