views:

204

answers:

2

I'm tying to collect all Custom Attributes placed over a Property. There are more than one Attributes of the same type assigned to the Property, but when collecting them , the resulting collection only contains the first Attribute of the specific type:

The Attribute class

[AttributeUsage(System.AttributeTargets.Property,
               AllowMultiple = true)]

public class ConditionAttribute : Attribute{...}

Usage:

[ConditionAttribute("Test1")]
[ConditionAttribute("Test2")]
[ConditionAttribute("Test3")]
public Color BackColor{get; set;}

Now when looping through all Props of the object 'value' whose class contains the Prop "BackColor":

foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value))
{
  foreach (Attribute attribute in property.Attributes)
  {   ... }
   ....
}

the collection property.Attributes only contains ONE Attribute of type "ConditionAttribute" : The one with "Test1". The others are ignored;-(

So does AllowMultiple not work for Property Attributes ?

Thanks in advance

henrik

A: 

Yes, it does work. Not sure why it does not work via PropertyDescriptors.

You can always do: Attribute.GetCustomAttributes(methodInfo, typeof(ConditionAttribute))

leppie
+3  A: 

According to a post on MSDN, this is by design as part of the PropertyDescriptor class.

However, you can actually solve the problem by overriding TypeId in your custom attribute (Thanks to Ivan from Mindscape for pointing this out):

public override object TypeId
{
  get
  {
    return this;
  }
}
mcdrewski