Reputation: 2265
I will try to explain what I need.
Let's say that I have a class like this:
Public Class Example1
Public Sub ToBeCalled()
System.Console.WriteLine(
"The Method or Class or file and its line which called me is: ",
?????)
End Sub
End Class
Then I have a second class like this:
Public Class Second
Public Sub SomeProcedure()
Dim obj As Example1 = New Example1
obj.ToBeCalled()
End Sub
End Class
Module1
Dim obj2 As Second = New Second()
obj2.SomeProcedure()
End Module1
And what I would like to get on the screen instead of "????" is:
1) The Method or Class or file and its line which called me is: Second
2) The Method or Class or file and its line which called me is: SomeProcerure
3) ...... is: Second.vb
4) ...... is: line 54
5)....... is: col 33
Can anybody help me please?
Upvotes: 1
Views: 1637
Reputation: 5299
In order to get caller (also column and line numbers) you should use System.Diagnostics.StackTrace class.
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
Upvotes: 0
Reputation: 74530
You can always use the StackTrace class. This will allow you to walk the stack in order to find out information about the methods that lead to your method being called.
In your case, you will want to use the StackFrame class, as you want only one particular frame (you could use the StackTrace class, but it will do an entire trace, and in this case, you just want one frame). With a StackTrace instance, you can call the GetMethod method to obtain the MethodBase instance which represents the method that is making the call.
Here's an example, it's in C#, but easily translatable to VB.NET:
// Skip the current stack frame, get the caller.
StackFrame stackFrame = new StackFrame(1);
// Print out the method name.
Console.WriteLine(stackFrame.GetMethod().Name);
Note that if you wanted additonal information like the line number, etc, etc, you have to provide a debug build with the PDB file.
Upvotes: 1
Reputation: 172270
The StackTrace class might be able to provide you with the required information.
A simpler way to access this information is currently being considered for VB 11: Lucian's VBlog: Power6: CALLER_MEMBER.
Upvotes: 0
Reputation: 887453
You're looking for the StackTrace
class.
Note that you can only get line numbers in a debug build with a PDB file.
Also note that you should add <MethodImpl(MethodImplOptions.NoInlining)> _
before the method.
Upvotes: 0