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 scope1: 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 scope even though it was defined in the For...Next loop. In VB .NET, D has block scope and line 7 causes the error The name D is not defined (see Listing 2.13 for a revision). Listing 2.13 VB .NET supports block scopeSub BlockScope() Dim I, D As Integer For I = 1 To 100 D = D + 1 Next I MsgBox End Sub For D to be accessible outside the For...Next statement, the variable must be defined outside the For...Next loop; that is, D must be defined in the scope in which it's used. Any variable defined in an outer scope is visible to narrower scopes but not broader scopes. For example, a procedure variable, like D, is visible to the For...Next block's scope, which is narrower than the procedure but not accessible outside of the procedure. |
Team-Fly |
Top |