0

It's possible to obtain a reference of the object that use an attribute?

E.g.:

public class Test {
    [MyAttribute]
    public string P {get;set;}
}
var k = new Test();

public class MyAttribute : Attribute
{
    public void Invoke(){
        //Can I get here a reference to k at runtime?
    }
}

With [CallerMemberName] I can know which property calls the attribute but I don't know how to get the caller itself.

GSerg
  • 76,472
  • 17
  • 159
  • 346
gidanmx2
  • 469
  • 1
  • 9
  • 24
  • Nope, can't think of any way. – Tanveer Badar Sep 28 '20 at 17:07
  • realistically, no, in theory you could use unsafe code to look through your entire application's memory looking for objects, and seeing if any of those objects have a property with that attribute. It would be both very slow and extremely hard to do correctly though. – Servy Sep 28 '20 at 17:10
  • Attributes are for defining metadata related to the static definition of a method (among other things). I'm struggling to think of a situation where you would have access to that metadata without knowing what the metadata belonged to. – Abion47 Sep 28 '20 at 17:12
  • Does this answer your question? [Can C# Attributes access the Target Class?](https://stackoverflow.com/q/2308020/11683) – GSerg Sep 28 '20 at 17:15
  • There isn't an attribute per instance of the class, so there's nothing to tie the `MyAttribute` instance to the instance referred to by `k`. – Jon Skeet Sep 28 '20 at 17:15
  • 1
    _Objects_ don't use attributes. _Type definitions_ use attributes. Attributes are not associated with instances. – Jeff Sep 28 '20 at 17:15

0 Answers0