Reflection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,


How can I get the type of the caller of a method via reflection ? I want
to know what type actually called the method.

For example.

Class A method Afn() calls Class B method Bfn()

How can I actually programatically via reflection inside Bfn() get the
C.Afn() type that actually called this?
 
How can I get the type of the caller of a method via reflection ? I want
to know what type actually called the method.

For example.

Class A method Afn() calls Class B method Bfn()

How can I actually programatically via reflection inside Bfn() get the
C.Afn() type that actually called this?

Do you mean the instance of A? You can't. If you need it, make it a
parameter in the method.
 
I can, I used the StackFrame :D

System.Diagnostics;

StackTrace, StackFrame and MethodBase you can get the info.

Obviously its the 2nd item on teh call stack that called the method.

I was hoping there was a nicer way but this way works and as its a debug
option its not too critical.
 
I can, I used the StackFrame :D

System.Diagnostics;

StackTrace, StackFrame and MethodBase you can get the info.

No it can't. It can get the *type*, but not the *instance*, which is
why I asked whether or not you meant the instance.
Obviously its the 2nd item on teh call stack that called the method.

I was hoping there was a nicer way but this way works and as its a debug
option its not too critical.

Don't forget that it may not be accurate (due to inlining etc).
 
I dont want the actual instance, just where it was called.

As for inlining, well at lesat I will have the ReflectedType from
MethodBase, so its better than nothing.
 
I dont want the actual instance, just where it was called.
Right.

As for inlining, well at lesat I will have the ReflectedType from
MethodBase, so its better than nothing.

My point is that you might have missed a few stack frames. For
instance, the stack could theoretically be:

Foo.SomeMethod
Bar.SomeInlinedMethod
Gronk.AnotherInlinedMethod
Baz.SomeBigMethod

and the stack that you get back in the stack trace could be:

Foo.SomeMethod
Baz.SomeBigMethod
 
Thtats why optimization = off for debug builds, right.

Is there anyway to get where this was called in optimized builds (with
inlining), i just need the actual namespace, class and method that actually
called this (according to my actual code).
 
Thtats why optimization = off for debug builds, right.

Is there anyway to get where this was called in optimized builds (with
inlining), i just need the actual namespace, class and method that actually
called this (according to my actual code).

I don't believe so. In practice, I think it will *often* get it right,
but it's not guaranteed.
 
Back
Top