11

I need to find the type of the property that a custom attribute is applied to from within the custom attribute.

For example:

[MyAttribute]
string MyProperty{get;set;}

Given the instance of MyAttribute, how could I get a Type descriptor for MyProperty?

In other words, I am looking for the opposite of System.Type.GetCustomAttributes()

Adrian Grigore
  • 33,034
  • 36
  • 130
  • 210

2 Answers2

21

The attribute itself knows nothing about the object that was decorated with it. But you could inject this information at the time you retrive the attribute.
At some point you have to retrieve the property using code similar to the following.

PropertyInfo propertyInfo = typeof(MyType).GetProperty("MyProperty");

Object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyAttribute), true);

if (attribute.Length > 0)
{
    MyAttribute myAttribute = (MyAttribute) attributes[0];

    // Inject the type of the property.
    myAttribute.PropertyType = propertyInfo.PropertyType;

    // Or inject the complete property info.
    myAttribute.PropertyInfo = propertyInfo;
}
luvieere
  • 37,065
  • 18
  • 127
  • 179
Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
  • I needed this for my problem and I found [another solution here](https://stackoverflow.com/questions/4879521/how-to-create-a-custom-attribute-in-c-sharp/44595783#answer-4879579). I elaborated on this and posted a response for accessing a custom attribute on a property and not a class, too. Thank you, by the way! – Hopper Jun 16 '17 at 18:30
4

The custom attribute knows nothing about the attributed element so I don't think what you want is possible to do unless you enumerate all types in your system and check if they contain such attribute.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228