Implicit Reference to parent class?

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

Is there any way in a generic class object to implicitly get a reference to
the class that instantiated that object ? Obviously I can pass it a
reference to store but it would be nice if there was an implicit Parent
property or something similar that gave you it "for free".
 
JezB said:
Is there any way in a generic class object to implicitly get a reference to
the class that instantiated that object ? Obviously I can pass it a
reference to store but it would be nice if there was an implicit Parent
property or something similar that gave you it "for free".

Nope, there's nothing like that - good job too, otherwise it would be a
waste of space for the vast majority of cases, which don't require it.
 
Actually, you can. In your constructor call:

System.Diagnostics.StackFrame frame = new StackFrame(2);
Type callingClass = frame.GetMethod().DeclaringType;

Note that this won't give you the instance that called your constructor, only the class. But that's what you asked for, so hopefully this will work for you. If this is a high-performance application, using Diagnostics may carry a higher cost than you want to pay. But otherwise, this should be fine. BTW, you may need to up the stack frame count (the argument to the StackFrame constructor) if there are more method calls between your constructor and the class that's creating it (e.g., if multiple constructors are called due to subclassing, etc). Hope this helps.

- Ben Blair
{My Name} {at} acm.org

----- JezB wrote: -----

I see your point ! I just wanted to be sure I wasnt missing something ...
 
Ben Blair said:
Actually, you can. In your constructor call:

System.Diagnostics.StackFrame frame = new StackFrame(2);
Type callingClass = frame.GetMethod().DeclaringType;

Note that this won't give you the instance that called your
constructor, only the class. But that's what you asked for,
so hopefully this will work for you.

Except it might not work, because of inlining. All in all, it's a
pretty dodgy thing to rely on, IMO. Far better is to either remove the
need from the design in the first place, or get the caller to pass in a
reference to themselves (or their type, if that's all that's required).
 
Back
Top