Variable Scope Changes in VB .NET

Visual Basic .NET supports block-level scope. Generally, it's best to declare variables in as narrow a scope as possible; this rule directly supports the “don't-use-global-variables” rule.

VB6 variables within a For...Next loop are accessible in the scope containing the For...Next loop. Visual Basic .NET variables in a For...Next loop aren't accessible in the outer scope. Listing 2.12 demonstrates VB6 scope and Listing 2.13 demonstrates the block scope revision in VB .NET.

Listing 2.12. VB6 scope is limited to procedure scope
						1: Private Sub Command6_Click()
2:   Dim I As Integer
3:   For I = 1 To 100
4:     Dim D As Integer
5:     D = D + 1
6:   Next I
7:   MsgBox D
8: End Sub

In VB6, line 7 displays 100. D has procedure ...

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.