HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpCritical

How can I find the method that called the current method?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcalledfindthemethodcurrentcanthat

Problem

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods.

Solution

Try this:

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace(); 
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);


one-liner:

(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name

Code Snippets

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace(); 
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
(new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name

Context

Stack Overflow Q#171970, score: 678

Revisions (0)

No revisions yet.