Reputation: 122132
I would like to use reflection in .NET to get access to the object that invoked my method. I assume it is somehow possible to view up the stacktrace. I know it's not safe for a variety of reasons, but I just need to grab and catalog some property values.
How do I do this?
Update: I'm an idiot, I forgot to say this was in C#
Upvotes: 4
Views: 3298
Reputation: 2376
You may use the StackTrace & StackFrame classes
here is an example from MSDN
http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.aspx
This is an example, which should print "Main"
class Program
{
static void Main(string[] args){
Func();
}
static void Func(){
StackFrame frame = new StackFrame(1);
StackTrace trace = new StackTrace(frame);
var method = frame.GetMethod();
Console.WriteLine(method.Name);
}
}
Upvotes: 2
Reputation: 22492
var methodInfo = new StackFrame(1).GetMethod();
Returns the method that called the current method.
Note that the compiler may inline or otherwise optimize calls to methods (although that sounds like it might not be the case for you), which thwarts expected behavior. To be safe, decorate your method with:
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
Note that this goes contrary to allowing the compiler to do its job. Caveat emptor.
EDITED Oops, I see that you want the instance that invoked your method. There's no way to get that information.
Upvotes: 5
Reputation: 110121
What if a static method calls you?
Wouldn't it be a better (simpler) contract with the caller if they passed themself to you?
Upvotes: 2