Get the name of the currently executing .NET method at runtime

With .NET you can get the name of the currently executing method, or its calling method, dynamically. This is useful when writing to error logs or displaying error messages so you know exactly what method failed. You do this by using the StackFrame, StackTrace and MethodBase classes in the System.Diagnostics and System.Reflection namespaces.

StackFrame:
Provides information about the function call on the stack for the current process.

StackTrace:
Is a collection of all the StackFrames on the stack.

MethodBase:
Is an abstract class that contains information about currently executing method.

As you probably know, when an exception occurs in a method, the Exception object in your Try/Catch block contains a reference to the StackTrace object that you can use to retrieve the method's name. However, to get a method's name when no error is generated, you must get it from the stack via the StackFrame class.

VB.NET Code to display the name of the executing method:

   Imports System.Reflection
   Imports System.Diagnostics
    
   Private Sub GetMyName() 
      Dim sf As StackFrame = New StackFrame()
      Dim mb As MethodBase = sf.GetMethod()
      Console.WriteLine(mb.Name ) ' Displays “GetMyName”
      WhoCalledMe()
   End Sub

   Private Sub WhoCalledMe() 
      Dim st As StackTrace = New StackTrace()
      Dim sf As StackFrame = st.GetFrame(1)
      Dim mb As MethodBase = sf.GetMethod()
      Console.WriteLine("I was called by: " & mb.Name ) ' Displays “GetMyName”
   End Sub

   '
   ' Get the namespace the method belongs to:
   '
   '...
   Dim sf As StackFrame = st.GetFrame(1).DeclaringType.ToString()   

These classes contain a wealth of information on the attributes and parameters of the current method, the currently executing line of code... However, much of this information is only available when the application is compiled in Debug mode.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page