Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the referring method in VB.NET?

Tags:

vb.net

See this example:

''//file1.vb
Sub Something()
    ''//...
    Functions.LogInfo("some text")
    ''//...
End Sub

''//functions.vb
Sub LogInfo(ByVal entry as String)

    Console.WriteLine(entry)

End Sub

Can I get the the name "Something" inside LogInfo?

Sorry for the briefness of this post, I am not sure how to properly articulate this question. I will clarify and elaborate as needed.

like image 646
Anders Avatar asked Apr 03 '09 19:04

Anders


2 Answers

(EDIT: Removed unnecessary use of StackTrace itself - which would be useful if you wanted to print out more info than just one frame.)

You can use the StackFrame class, but it's pretty expensive (IIRC) and may be slightly incorrect due to inlining.

EDIT: Something like this: (the NoInlining is to make sure it behaves properly...)

Imports System.Diagnostics
Imports System.Runtime.CompilerServices

Public Class Test

    Shared Sub Main()
        Something()
    End Sub        

    <MethodImpl(MethodImplOptions.NoInlining)> _
    Shared Sub Something()        
        Functions.LogInfo("some text")
    End Sub

End Class

Public Class Functions

    <MethodImpl(MethodImplOptions.NoInlining)> _
    Public Shared Sub LogInfo (ByVal entry as String)
        Dim frame as StackFrame = new StackFrame(1, False)
        Console.WriteLine("{0}: {1}", _
                          frame.GetMethod.Name, _
                          entry)
    End Sub

End Class
like image 118
Jon Skeet Avatar answered Sep 23 '22 13:09

Jon Skeet


Take a look at How can I find the method that called the current method?.

Translated to VB (Hopefully):

Imports System.Diagnostics
''// get call stack
Dim stackTrace As New StackTrace()

''// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name)
like image 37
Quintin Robinson Avatar answered Sep 23 '22 13:09

Quintin Robinson