Get name of current method in C#
This post will discuss how to get the name of the current method being executed in C#.
1. Using StackTrace Class (System.Diagnostics)
A stack trace is an ordered collection of one or more stack frames that store debugging and diagnostic information.
The following example creates a simple stack trace using the StackTrace instance. The second frame of the stack trace contains the stack frame of the current method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Diagnostics; public class Example { public static string GetCurrentMethodName() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); return stackFrame.GetMethod().Name; } public static void Main() { string currentMethod = GetCurrentMethodName(); Console.WriteLine(currentMethod); } } /* Output: Main */ |
If you don’t want to create a helper method, change the code to the following. Here the first frame represents the top of the stack, which is the last method invocation in the sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Diagnostics; public class Example { public static void Main() { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(0); string currentMethod = stackFrame.GetMethod().Name; Console.WriteLine(currentMethod); } } /* Output: Main */ |
Or
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Diagnostics; public class Example { public static void Main() { StackFrame stackFrame = new StackFrame(0); string currentMethod = stackFrame.GetMethod().Name; Console.WriteLine(currentMethod); } } /* Output: Main */ |
2. Using MethodBase.GetCurrentMethod() method
Alternatively, the MethodBase.GetCurrentMethod() method can be used, which returns a MethodBase object representing the currently executing method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Diagnostics; using System.Reflection; public class Example { public static void Main() { string currentMethod = MethodBase.GetCurrentMethod().Name; Console.WriteLine(currentMethod); } } /* Output: Main */ |
That’s all about getting the name of the current method in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)