Jerad Rose
Jerad Rose

Reputation: 15513

Why is System.ComponentModel.DataAnnotations.DisplayAttribute sealed?

I was going to implement a custom DisplayAttribute in order to allow dynamic display values based on model values, but I can't because DisplayAttribute is sealed.

Before I go off and write my own customer attribute that emulates the behavior of DisplayAttribute, can anybody think of why this is sealed? I'm assuming there is a reason behind it, and if so, that may be the same reason I shouldn't try to "hack" around this limitation by rolling my own.

I'm not asking anyone to read Microsoft's mind, I'm just hoping someone already knows the by-design reason it's sealed, so that I can take that into account when rolling (or avoiding) my own implementation.

Upvotes: 4

Views: 1761

Answers (2)

nikmd23
nikmd23

Reputation: 9103

Not exactly what you asked, but following your intent...

You can still allow for dynamic display values, you just wont extend the DisplayAttribute.

Instead, you can implement your own IModelMetadataProvider which could contain any logic needed to create dynamic display values.

Brad Wilson, from the ASP.NET MVC team, has a good article and sample of this on his blog: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html

Upvotes: 0

bhamlin
bhamlin

Reputation: 5197

In general it is considered best practice to seal attributes. FxCop has a rule about it, defined here. From that page:

The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.

Many of the MVC attributes (ActionFilter, etc) are unsealed because they are specifically designed to be extended, but elements in the DataAnnotations namespace are not.

Upvotes: 7

Related Questions