1. Computing & Technology

Discuss in my forum

Block Level Scope in VB.NET

It's a good idea, but there are hidden problems.

By , About.com Guide

See More About:

If you remember coding in VB6, you might remember that this code would work fine:

 Dim Ans As String
 Ans = InputBox("")
 Dim I As Integer
 I = 10
 If Ans = "Yes" Then
    ' This worked fine in VB6
    ' N has procedure scope in VB6
    Dim N As Integer
    N = I
 End If
 MsgBox(N) 

One of the changes in VB.NET is called "block level" scope. The statements between If and End If are a block and since N is declared inside the block, it doesn't work anymore. Your first impression might be that this is a great way to tighten up your code by getting rid of variable declarations for entire procedures when all you need is a counter or flag inside a block. But there could be some problems.

VB.NET added block level scope to allow you to "tune" your program by restricting the scope of a variable when it's only needed in a block. Microsoft's own example however, from VB.NET Help, is a For-Next loop, not an IF block. Here's a simplified version of the example in VB.NET Help:

 Dim I As Integer
 For I = 1 To 3
    Dim N As Long
    ' N has block scope in VB.NET
    N = N + I
 Next 

There are two interesting consequences to this.

First, there is no way to initialize the value N inside the For-Next loop. If you wanted to start N out with a value of, for example, 10 instead of the default value 0, you would have to declare it outside the For-Next loop and that would make it a procedure level declaration instead of a block level declaration. So what would be the point?

Second, the scope of the variable may be the For-Next block, but the lifetime is still the life of the program. An example of this can be seen in this code:

 Dim J As Integer
 For J = 1 To 2
    For I = 1 To 3
       Dim N As Long
       Console.WriteLine("Value of N: {0}", N)
       ' N has block scope in VB.NET
       N = N + I
    Next
    Console.WriteLine("We have exited the block!")
 Next 

Output:

 Value of N: 0
 Value of N: 1
 Value of N: 3
 We have exited the block!
 Value of N: 6
 Value of N: 7
 Value of N: 9
 We have exited the block! 

As you can see, N retains its value after exiting the inner loop block. Since it can't be reinitialized outside the loop because that's outside the block, this is another reason why you might check your logic before depending on block level scoped variables.

If you have a different point of view, let me know!

©2012 About.com. All rights reserved.

A part of The New York Times Company.