Welcome to my article. Today, I will demonstrate how to use the System.Reflection class' methods to get various information on which methods called certain methods.
In a large program, it sometimes can get cumbersome to know from where a certain message came from. By using classes such as StackTrace and MethodBase, you can easily find out the message calling information.
The System.Reflection namespace contains types that retrieve information about modules, members, assemblies, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types. Here is more information on the System.Reflection Namespace.
StackTrace represents a stack trace, which is an ordered collection of one or more stack frames. Here is more information on StackTraces. All messages get loaded onto a stack, and you can use StackTrace to trace where a certain method is in the current message stack.
The StackFrame class provides information about a StackFrame, which represents a function call on the call stack for the current thread. Read here for more information:
The MethodBase class provides information about methods and constructors, and where they come from. Here is more information:
Start Visual Studio and create a new Visual Basic Windows Forms project. Add two buttons to the form's design.
Add the following code to get the current executing method's name:
Private Sub GetCurrentMethodName() Dim sfFrame As StackFrame = New StackFrame() Dim mbMethod As MethodBase = sfFrame.GetMethod() MessageBox.Show(mbMethod.Name) End Sub
Here, I created a new StackFrame object, from which I created a MethodBase object. Then, I simply show the current method's name inside a MessageBox.
Call this function with the following piece of code:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click GetCurrentMethodName() End Sub
Add the following code to find out which method called a certain method:
Private Sub WhoCalledTheMethod() Dim stTrace As StackTrace = New StackTrace() Dim sfFrame As StackFrame = stTrace.GetFrame(1) Dim mbMethod As MethodBase = sfFrame.GetMethod() MessageBox.Show("I was called by: " & mbMethod.Name) End Sub
In the preceding code, I created a StackTrace object and then a StackFrame and a MethodBase object to determine the method caller. Lastly, I simply display the result inside a MessageBox.
Although this article was a bit short, it was quite powerful and a good way to find out calling information from methods via the StackTrace class. Until next time, cheers!