Retrieving the Name of the Current Executing Method

  • Thread starter Thread starter clr
  • Start date Start date
C

clr

I like to stamp trace logs with the name of the executing Class and Method.
I can get the Class Name using GetType.Name and I can get a list of every
Method in the class using System.Reflection.MethodInfo objects (code
follows) But is there anyway to retrieve the name of the currently
executing Method? Or is this a lost cause?

(code sample)
Dim sClassName as String = Me.GetType.Name
Dim aMethod() as System.Reflection.MethodInfo =
Me.GetType.GetMethods(BindingFlags.Public or BindingFlags.Instance or
BindingFlags.DeclaredOnly)
Each member of aMethod has a Name property giving me a complete list of all
of the Class Methods.

Thanks
clr
 
* "clr said:
I like to stamp trace logs with the name of the executing Class and Method.
I can get the Class Name using GetType.Name and I can get a list of every
Method in the class using System.Reflection.MethodInfo objects (code
follows) But is there anyway to retrieve the name of the currently
executing Method? Or is this a lost cause?

\\\
MsgBox(System.Reflection.MethodBase.GetCurrentMethod().Name)
///

--
Herfried K. Wagner
MVP · VB Classic, VB.NET
<http://www.mvps.org/dotnet>

Improve your quoting style:
<http://learn.to/quote>
<http://www.plig.net/nnq/nquote.html>
 
clr,
You can use either the StrackTrace or StackFrame classes, both in the
System.Diagnostics namespace.

Both support skipping frames (current method), so you can encapsulate the
use of StackTrace or StackFrame in its own method, and not see the
encapsulating method.

Hope this helps
Jay
 
Hi clr, Jay,

Here's a StackTrace version:

Public Function MeAndMyCaller As String
Dim CurrentStack As New System.Diagnostics.StackTrace

Dim Myself As String = CurrentStack.GetFrame(0).GetMethod.Name _
& " "
&CurrentStack.GetFrame(0).GetFileLineNumber

Dim MyCaller As String = CurrentStack.GetFrame(1).GetMethod.Name _
& " "
&CurrentStack.GetFrame(1).GetFileLineNumber

Return "In " & Myself & vbCrLf & "Called by " & MyCaller
End Function

Regards,
Fergus
 
Herfried, Jay, and Fergus

I situations where both the MethodBase.GetCurrentMethod and Stack Frame
example are helpful.
Your advise is appreciated.
clr
 
When working with the Exception Stack Trace Object is there a way to extract
the Line Number without parsing the returned string?

clr
 
Hi clr,

Given that Exception StackTrace <is> a string means that you <do> have to
parse it for the line number.

Presumably you are getting this information from an Exception in the Catch
of one of the calling methods - and not where the Exception actually occurred?

Regards,
Fergus
 
* "clr said:
When working with the Exception Stack Trace Object is there a way to extract
the Line Number without parsing the returned string?

General information: The line number will only be available when
compiling in debug mode.
 
Back
Top