Using Static Variables

The mechanics for declaring static variables require that you replace Dim with Static as demonstrated in the following function:

Function GetCounter() As Integer
  Static Counter As Integer = 0
  Counter += 1
  Return Counter
End Function

Each time GetCounter is called, Counter will be incremented by 1. The first time GetCounter is called it will return 1, and each subsequent call to GetCounter will return Counter + 1. (Note the use of the new addition and assignment operator, +=.)

Caution

You cannot use the compound operators, like +=, in an initialization statement for a variable. For example, Static Counter As Integer += 1 will cause a compiler error.

A function like GetCounter is a good way to get a unique value during ...

Get Visual Basic® .NET Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.