Home > Articles

  • Print
  • + Share This
This chapter is from the book

Preserving Data Between Procedure Calls

Suppose that you want to keep track of the number of times you've called a procedure. You might write a function like Tracker in this code, which has a variable named intCount that it increments each time you call the function:

Module Module1

  Sub Main()
    For intLoopIndex As Integer = 0 To 5
      Console.WriteLine(Tracker())
    Next intLoopIndex
    Console.WriteLine("Press Enter to continue...")
    Console.ReadLine()
  End Sub

  Function Tracker() As Integer
    Dim intCount As Integer
    intCount += 1
    Return intCount
  End Function

End Module

Because the code calls Tracker six times and displays its return value each time, you might expect to see this program display 1, 2, 3, 4, 5, and 6. But you actually get this result:

1
1
1
1
1
1
Press Enter to continue...

The problem here is that the intCount variable in Tracker is re-initialized to 0 each time the procedure is called, so the return value, after intCount is incremented, is always 1. The solution is to declare intCount as static, as shown in Listing 3.5 and the Static project in the code for this book.

Listing 3.5 Using Static Variables (Static project, Module1.vb)

Module Module1

  Sub Main()
    For intLoopIndex As Integer = 0 To 5
      Console.WriteLine(Tracker())
    Next intLoopIndex
    Console.WriteLine("Press Enter to continue...")
    Console.ReadLine()
  End Sub

  Function Tracker() As Integer
    Static intCount As Integer
    intCount += 1
    Return intCount
  End Function

End Module

Now the value in intCount is preserved between calls to the Tracker function, and you do indeed see the result 1, 2, 3, 4, 5, and 6.

Besides using the Static keyword, you can also make intCount a module-level variable to do the same thing, by taking it out of any procedure:

Dim intCount As Integer

Function Tracker() As Integer
  intCount += 1
  Return intCount
End Function

The result here is the same as using Static to declare the variable; because the variable is outside any procedure, its value isn't reset when you call a procedure.

TIP

To declare module-level variables, you place the declaration outside any procedure in the module. You can also select the module in the left drop-down list box at the top of the code designer and the (Declarations) item in the right drop-down box, which will place the cursor at the beginning of the module, outside any procedure.

Making a variable into a module-level variable outside any procedure like this introduces the idea of scope. Here, the scope of this new variable is module-level scope. The scope of an item in your program is the area in which it's accessible in your code, and there are all different types of scope—module-level, procedure-level, block-level, and more. And we'll look at this issue next.

  • + Share This
  • 🔖 Save To Your Account