2

How can i determine if an attribute can be applied to a class using reflection?

I am currently pulling the collection of attribute types using reflection, basically:

  • GetAssemblies
  • GetTypes
  • Where base type is type of Attribute

then getting the constructors to get each available signature.

I only need the attributes that can be applied to a class, but not sure where to find the usage definition using reflection.

arserbin3
  • 6,010
  • 8
  • 36
  • 52
opdb
  • 221
  • 1
  • 3
  • 12
  • possible duplicate of [how to get both fields and properties in single call via reflection?](http://stackoverflow.com/questions/12680341/how-to-get-both-fields-and-properties-in-single-call-via-reflection) – Jeff May 23 '14 at 17:44
  • This doesnt have to do with fields and properties. Im trying to get the attribute usage.. since an attribute can be applied only to a method, or only to a class, or both. – opdb May 23 '14 at 17:45
  • point taken. i would guess that any attribute can be applied to any class and it would still compile. – Jeff May 23 '14 at 17:50
  • hmm.. you may be right, for some reason i was under the impression that it would not. let me give it a quick test – opdb May 23 '14 at 17:53
  • error CS0592 The attribute `SomeMethodAttribute' is not valid on this declaration type. It is valid on `method' declarations only – opdb May 23 '14 at 17:55

2 Answers2

2

You need to get the AttributeUsageAttribute on the Attribute class.

You've already gotten all the Attribute types, so you're nearly there. Call GetCustomAttributes() on each type. If the attribute type has no usage attribute, I believe it can be used anywhere. If it does have a usage attribute, read the ValidOn property to see if it includes AttributeTargets.Class.

var attributes = attributeType.GetCustomAttributes(typeof(AttributeUsageAttribute), true);
if(attributes.Length == 0 || (attributes.Length > 0 && ((AttributeUsageAttribute)attributes[0]).ValidOn & AttributeTargets.Class) != 0))
{
   //is class-valid attribute
}
Rex M
  • 142,167
  • 33
  • 283
  • 313
  • Too many `Attribute`s in this answer. My head is starting to hurt ;) – Jeff May 23 '14 at 18:08
  • 2
    @Jeff what, you don't find attributing attributes with AttributeAttribute attributes to be intuitive? – Rex M May 23 '14 at 18:10
0

Try this method. You need to get the attributes of the attribute.

public bool IsClassAttribute(Type attribute)
{
    object[] attributeUsage = attribute.GetCustomAttributes(typeof(AttributeUsageAttribute), true);
    if (attributeUsage == null || attributeUsage.Length <= 0) return false;
    AttributeUsageAttribute aua = attributeUsage[0] as AttributeUsageAttribute;
    return aua != null && (aua.ValidOn & AttributeTargets.Class) != 0;
}
Bartosz Wójtowicz
  • 1,321
  • 10
  • 18