Valentin V
Valentin V

Reputation: 25739

When to use attributes instead of properties?

Are there specific cases when one should use custom attributes on class instead of properties? I know that properties are preferrable because of their discoverability and performance, but attributes... When should I definitely use them?

UPDATE:

Here is a post by Eric Lippert about this decision.

Upvotes: 12

Views: 3388

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500555

Eric Lippert has a great blog post tackling exactly this decision.

His summary is:

In short: use attributes to describe your mechanisms, use properties to model the domain.

I'd also add to that the consideration that an attribute value is effectively static - in other words it's part of the description of the type rather than any instance of the type.

One tricky bit can come when every instance of some base type has to have a property (e.g. a description) but different concrete derived types want to specify descriptions on a per-type basis rather than per-instance. You often end up with virtual properties which always return constants - this isn't terribly satisfactory. I suspect Delphi's class references might help here... not sure.

EDIT: To give an example of a mechanism, if you decorate a type to say which table it's from in the database, that's describing the data transfer mechanism rather than saying anything about the model of data that's being transferred.

Upvotes: 15

Two Bit Gangster
Two Bit Gangster

Reputation: 993

There are two use cases:

1) Using a custom attribute that someone else has defined, such as the System.LoaderOptimization attribute that may be used on the Main method. These kinds of attributes are used to direct platform code such as the CLR, WPF, WCF or the debugger to run the code in a certain way, and can be very useful at times. Reading books on various platform topic is a good way to learn when and how to use these attributes.

2) Creating your own custom attribute and using it to decorate a class (or method, property, etc). These have no effect unless you also have code that uses Reflection to notice those attribute usages and change the behavior in some way. This usages should be avoided whenever possible because of very poor performance, orders of magnitude larger than, say, accessing a static member of a class.

Upvotes: 0

Related Questions