Scope and Modules
Prerequisites: Subs and functions
Scope is where a name can be used.
Block, procedure, and module scope
Module Program
Private counter As Integer = 0 ' module-level: whole module
Sub Increment()
counter += 1
End Sub
Sub Main()
Dim message = "local to Main" ' procedure-level
For i = 1 To 3
Dim doubled = i * 2 ' block-level: only inside the loop
Increment()
Next
Console.WriteLine($"{message}, counter = {counter}")
End Sub
End Module
local to Main, counter = 3
Declare variables in the smallest scope that works. Module-level variables are shared by every procedure in the module, which makes programs harder to follow when overused.
Several modules
A program can have many modules. Public members are visible from other
modules; Private ones are not:
Module Temperature
Public Const FreezingC As Double = 0
Public Function ToFahrenheit(c As Double) As Double
Return c * 9 / 5 + 32
End Function
Private Function Helper() As String
Return "hidden"
End Function
End Module
Module Program
Sub Main()
Console.WriteLine(ToFahrenheit(100))
Console.WriteLine(Temperature.ToFahrenheit(FreezingC))
End Sub
End Module
212
32
Members of a module can be used without the module name
(ToFahrenheit), though writing Temperature.ToFahrenheit makes the
origin clear. In a project, each module usually lives in its own .vb
file.
Access levels
| Keyword | Visible to |
|---|---|
Public |
everyone |
Friend |
code in the same project (assembly) |
Protected |
the class and classes that inherit from it |
Private |
only the containing module, class, or structure |
Dim at module level means Private.
Static local variables
A Static local variable keeps its value between calls:
Module Program
Function NextTicket() As Integer
Static number As Integer = 100
number += 1
Return number
End Function
Sub Main()
Console.WriteLine(NextTicket())
Console.WriteLine(NextTicket())
Console.WriteLine(NextTicket())
End Sub
End Module
101
102
103
(Note: VB's Static keyword means "remembered between calls", unlike
C#'s static, which VB calls Shared.)