Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use attributes instead of properties?

Tags:

c#

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.

like image 353
Valentin V Avatar asked Feb 16 '09 07:02

Valentin V


1 Answers

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.

like image 66
Jon Skeet Avatar answered Oct 14 '22 17:10

Jon Skeet