Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use C# reflection to access the object up the stacktrace

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#

like image 420
George Mauer Avatar asked Jan 23 '23 08:01

George Mauer


1 Answers

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.

like image 191
Ben M Avatar answered Jan 25 '23 21:01

Ben M