AllowMultiple property on System.AttributeUsageAttribute

I've been tripped up by this one many, many times!  For those of you who are really into your attributes (as I am), the AllowMultiple property is useful for when an attribute has to be applied to the same class definition multiple times. 

By default, AttributeUsage's AllowMultiple is set to false, meaning that you can only decorate a type/member with a given attribute once. 

Here's the exceprt from Patrick Steele's blog which explains further:

--------------------

I had designed a custom attribute for fields and wanted to be able to apply it multiple times. For example:

<ExtItem("A1", "Text"), ExtItem("A2", "Color")> _
Private label1 As System.Windows.Forms.Label

This produced an error: Attribute 'ExtItem' cannot be applied multiple times. A quick check of the documentation says "multiple instances of an attribute can be applied to the same target element". So what was I doing wrong?

Fellow MVP Mattias Sjogren pointed me to the AttributesUsage attribute:

<AttributeUsage(..., AllowMultiple:=True)> _
Public Class ExtItemAttribute
    ...

Thanks Mattias!

-------------------------

This reminds me of another attribute-ish point.  Thanks to FxCop for pointing me to this one.  Apparently, attributes should be declared as "sealed".  There is a significant performance degredation when using non-sealed attributes (although to me .NET reflection is so fast, I've personally never seen this particular problem).

1 Comment

  • Hmm, interesting. Is that recommendation in the docs anywhere?





    I've seen at least one common scenario where it's extremely useful (practically required) for attributes to be non-sealed. Attributes that store strings for display (in particular, designer attributes like CategoryAttribute) have no default way of returning localized strings. The standard trick I've seen used is to subclass the attribute and return a string read from a resource file.

Comments have been disabled for this content.