0

Let's say I have a property defined like below:

[SomeAttriubte("#1")]
public SomeClass Property1 { get; set; }

[SomeAttribute("#2")]
public SomeClass Property2 { get; set; }

Which SomeClass definition is something like this:

public class SomeClass
{
     private void PrivateMethod()
     {
           //Some action
     }
}

Is there any way to read SomeAttribute argument value in the PrivateMethod inside the defining type class??

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
evolon
  • 1,276
  • 1
  • 10
  • 18
  • The attributes can only be read on the class (type) that defines the properties. see here http://stackoverflow.com/questions/2656189/how-do-i-read-an-attribute-on-a-class-at-runtime – Ric Jun 16 '15 at 14:09
  • So there's no way to read the values from the SomeClass body, right? Then what would be the best approach to ask the defining class to expose attributes data to the SomeClass class??? – evolon Jun 16 '15 at 14:12
  • @evolon In general there isn't... Even if the containing class passed the `this` to `SomeClass`, `SomeClass` wouldn't be able to distinguish the case where `Property1 == Property2` – xanatos Jun 16 '15 at 14:14

1 Answers1

2

No. The attributes you use are connected to the property. To be able to access them, SomeClass.PrivateMethod() would need to know the PropertyInfo of the properties it is used in. But it can't. To be more "clear": a type doesn't know "where" it is used, and not knowing "where" it is used, it can't access attributes connected to the place "where" it is used (in the same way that it can't access the this of the object "where" it is used)

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • @evolon I don't know... It all depends on what you want to do. Normally you would have a second class that "parses"/"analyzes" the "container" class and does "things"... But it is very abstract. Without knowing what you want to do, it is difficult to tell you how to do it. – xanatos Jun 16 '15 at 14:18