O'Reilly logo

Object-Oriented Programming with Visual Basic .NET by J.P. Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.3. The StackTrace Object

Whenever a method call is made, the Common Language Runtime creates information about that call. This information includes the location of the call within your program, the arguments that have been passed, and the local variables of the target method. The information is saved in a block of data called a stack frame. These stack frames are allocated in a region of memory called the call stack. The call stack contains all the methods that were called but have not returned to their callers. You saw this output to the console in Example 6-4.

This information can be very helpful when you track down bugs in your code. Even more helpful is the fact that you can inspect the call stack programmatically whenever you want. Example 6-5 demonstrates the process of iterating the call stack to obtain the method names that are currently active.

Example 6-5. Iterating the call stack
Imports System
Imports System.Diagnostics
Imports System.Reflection
   
Public Class StackTest
   
  Public Sub MethodA( )
    MethodB( )
  End Sub
   
  Public Sub MethodB( )
    MethodC( )
  End Sub
   
  Public Sub MethodC( )
   
    Dim i As Integer = 0
    Dim st As New StackTrace( )
    For i = 0 To st.FrameCount - 1
      Dim sf As StackFrame = st.GetFrame(i)
      Console.WriteLine(sf.GetMethod.Name)
    Next i
  End Sub
   
End Class
   
Public Class Application
   
  Public Shared Sub Main( )
    Dim test As New StackTest( )
    test.MethodA( )
    Console.ReadLine( )
  End Sub
   
End Class

The output from this program looks like this:

MethodC
MethodB
MethodA
Main

This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required