Get Calling Method using Reflection [C#]
To get name of calling method use method StackTrace.GetFrame. Create new instance of StackTrace and call method GetFrame(1). The parameter is index of method call in call stack. Index of the first (the nearest) method call is „1“, so it returns a StackFrame of the calling method (method which directly called the current method). To get the method name use StackFrame.GetMethod (to get MethodBase) and then just get value of Name property.
Following example shows how to get calling method name. This can be useful e.g. to write debugging logs.
[C#]using System.Diagnostics; // get call stack StackTrace stackTrace = new StackTrace(); // get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
See also
- [C#] Reflection Examples – examples how to use dynamically loaded assembly
- [C#] Get Call Stack – how to write method names from call stack
- [C#] Get Method Names using Reflection – get method names of any class
- StackTrace – MSDN – represents a call stack
- StackTrace.GetFrame – MSDN – gets stack frame of specific index
- StackFrame – MSDN – represents a function call on the call stack
- StackFrame.GetMethod – MSDN – gets stack frame of specific index
- MethodBase – MSDN – informations about a method including method name