Search Amazon:

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.

Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

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

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms