Question

public enum Animal
{
    [Description("King of jungle")]
    Lion= 1,

    [Description("Tallest there")]
    Giraffe = 2
}

Suppose I have the FieldInfo, I can go about it two ways:

//static one on 'Attribute' class
Attribute attribute = Attribute.GetCustomAttribute(field, 
                                                   typeof(DescriptionAttribute), 
                                                   false);

That's fine.

But the one below returns [] rather than Attribute ?

//instance one on 'MemberInfo` class
var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false);

This question is not really about MS' design choice. My question is should I be ever concerned about field.GetCustomAttributes returning multiple items for a specific attribute type? In what cases would that happen?

[Description("King of jungle")]
[Description("I'm a lion")]
Lion= 1

is never possible I guess. I think I should handle it when writing some reflection helper functions.

Was it helpful?

Solution

It makes perfectly sense to return multiple items per attribute type. Think of attributes designed with a base class. Or attributes where you could supply multiple options/types by constructor.

One example is the XmlArrayItemAttribute See the MSDN: XmlArrayItemAttribute Class

If you want to restrict your attributes to be only used once, you could add the allowmultiple:=False flag to your AttributeUsage.

@Comment

The DescriptionAttribute has AllowMultiple:=False (Which is the default if you don't specifiy it - at least in VB.NET). To get the effect, create your own attribute derived from Attribute and mark it with AttributeUsage where you set AllowMultiple = True.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top