Possible to get name of calling class and function?

D

Don

This may seem like an odd question, but is it possible to get the name of
the class & function that is calling a function of another class?

e.g.

Public Class CallerName
Public Shared Function Test() As String
Return <the name of my caller> ' <--- is there a way to do this?
End Sub
End Class

Public Class MyClass
Public Shared Sub MyFunction
Console.Write CallerName.Test '<-- spits out "MyClass.MyFunction"
End Sub
End Class


- Don
 
N

Nick Hall

Don said:
This may seem like an odd question, but is it possible to get the name of
the class & function that is calling a function of another class?

e.g.

Public Class CallerName
Public Shared Function Test() As String
Return <the name of my caller> ' <--- is there a way to do this?
End Sub
End Class

Public Class MyClass
Public Shared Sub MyFunction
Console.Write CallerName.Test '<-- spits out "MyClass.MyFunction"
End Sub
End Class


- Don
Have a look in the System.Diagnostics namespace at the classes StackTrace
and StackFrame. The StackTrace will allow you to obtain a reference to the
StackFrame above the current one (i.e. the calling method). You can then
obtain a System.Reflection.MethodBase which will contain all the information
you need. Note, this will probably only work as expected in Debug builds
(as the naming information is not available in Release builds).

Hope this helps,

Nick Hall
 
D

Don

Nick Hall said:
Have a look in the System.Diagnostics namespace at the classes StackTrace
and StackFrame. The StackTrace will allow you to obtain a reference to the
StackFrame above the current one (i.e. the calling method). You can then
obtain a System.Reflection.MethodBase which will contain all the information
you need. Note, this will probably only work as expected in Debug builds
(as the naming information is not available in Release builds).

Thanks for the tips. Here's what I ended up doing (more or less):


Dim strace As New StackTrace
Dim frame As New StackFrame
Dim method As System.Reflection.MethodBase

frame = strace.GetFrame(1) ' Gets the stack frame for the method that called
this one
method = frame.GetMethod ' Grab method info

Console.WriteLine(method.ReflectedType.Namespace & "." &
method.ReflectedType.Name & "." & method.Name)


- Don
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top