brady gaster

yadnb

what would this be called?

Say you've got two types. AType and BType. Inside of a method call, an instance of AType a creates an instance of BType b. So like this:

class AType
{
  void DoSomeWork()
  {
     BType b = new BType();
  }
}

Is there some way of reflecting (or remembering, i guess you could say) backwards in the stack to figure out what Type was the creating Type for your new instance?

Comments

Justin Rogers said:

The below program does this, but you have to be in debug mode. Else some of the StackTrace is actually missing and the StackFrame only returns the entry point of the executable. Kind of strange I'd say.

using System;
using System.Diagnostics;

public class PaganGod {
public void MyMethod() {
B b = new B();
b.WhoCreatedMe();
}
}

public class A {
public void MyMethod() {
B b = new B();
b.WhoCreatedMe();
}

private static void Main(string[] args) {
A a = new A();
a.MyMethod();

PaganGod pg = new PaganGod();
pg.MyMethod();
}
}

public class B {
private Type god_the_creator;

public B() {
StackFrame god_frame = new StackFrame(1);
god_the_creator = god_frame.GetMethod().DeclaringType;
}

public void WhoCreatedMe() {
Console.WriteLine(god_the_creator.ToString());
}
}
# February 3, 2004 10:21 PM

James Avery said:

If you plan on referencing the calling class, then it would be much better to pass in a reference to it in the constructor of your class then try to figure out something with reflection.

-James
# February 4, 2004 8:42 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)