Use Reflection to find a calling method

Reflection is a great way of finding the calling method in another method. I found this post which provided a good template for what I was trying to do (build a logging class that would automatically log the method and object that created the log entry). My code ended up being:

StackTrace stackTrace = new StackTrace();
// Calling Method and Object are only one frame up.
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string method = methodBase.Name;
string obj = methodBase.DeclaringType.Name;

Neat! I the write obj and method into my log…

Advertisement
Use Reflection to find a calling method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.