How to create duplicate allowed attributes

Viewed 38401

I'm using a custom attribute inherited from an attribute class. I'm using it like this:

[MyCustomAttribute("CONTROL")]
[MyCustomAttribute("ALT")]
[MyCustomAttribute("SHIFT")]
[MyCustomAttribute("D")]
public void setColor()
{

}

But the "Duplicate 'MyCustomAttribute' attribute" error is shown.
How can I create a duplicate allowed attribute?

6 Answers

Stick an AttributeUsage attribute onto your Attribute class (yep, that's mouthful) and set AllowMultiple to true:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class MyCustomAttribute: Attribute

AttributeUsageAttribute ;-p

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class MyAttribute : Attribute
{}

Note, however, that if you are using ComponentModel (TypeDescriptor), it only supports one attribute instance (per attribute type) per member; raw reflection supports any number...

As an alternative, think about redesigning your attribute to allow for a sequence.

[MyCustomAttribute(Sequence="CONTROL,ALT,SHIFT,D")]

or

[MyCustomAttribute("CONTROL-ALT-SHIFT-D")]

then parse the values to configure your attribute.

For an example of this check out the AuthorizeAttribute in ASP.NET MVC source code at www.codeplex.com/aspnet.

Related