1

Imagine a simple attrbute class. The attribute has been used on a property.
Can the Attribute Class "see" where it has been applied?

[AttributeUsage(AttributeTargets.Property)]
public class MyPropAttr : Attribute {
    public MyPropAttr () {
        PropName = ????; // default I was applied to prop X
    }
    public string SomeAttribute { get; set; }
    public string PropName { get; set; }   //<<<<<<<<< can this be determined ???
}

public class MyClass{
  [MyPropAttr(SomeAttribute="Bla")] 
  public string SomeFancyProp{ get; set; }
}
phil soady
  • 11,043
  • 5
  • 50
  • 95
  • 1
    No, the attribute only knows the implications of its constraints. Such as AttributeTargets.Class, AttributeTargets.Enum, etc. You can *get* the attributes of a property or class, but you can't *get* the property or class from an attribute. – Trevor Elliott Sep 30 '13 at 21:07
  • You'd need to reflect in the attribute constructor... it would just be an overall pain if even possible. – It'sNotALie. Sep 30 '13 at 21:08
  • Just curious, what's the use case? To get the attribute, you have to supply the name of the property anyway, so why is it important to know the property name from the attribute? – rsbarro Sep 30 '13 at 21:25
  • The only way is to set it when applying the attribute `[MyPropAttr(SomeAttribute="Bla",PropName="SomeFancyProp")]`. Reflection can only get `MyPropAttr.PropName` method (get_PropName) – MatteKarla Sep 30 '13 at 21:29
  • @ rsbarro, I dont like code that appears to state something that can be implied. I can change the use case so that attribute doesnt need to know. But i was curious if possible. Seems from link above that stackframe analysis would be possible but ugly. So you are right, when accessing an attribute, you should "know the property" it is on. But the attribute never knew. – phil soady Sep 30 '13 at 21:30
  • @Haim770 , thanks, some useful info there. – phil soady Oct 01 '13 at 03:19

0 Answers0