1. Technology

VB.NET Adds Block Level Scope

VB.NET gives you another code optimization choice!

By

Updated December 30, 2007

One of the changes in VB.NET in variable declaration is a new block level scope. This is a great new way to tighten up your code by getting rid of variable declarations for entire procedures when all you need is a counter or flag in a block. But there are some unusual features (??). To illustrate the situation, first check out this example of what has changed. First look at this VB6 code example:

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

Notice that there's no problem using the value of N outside of the If block. But when you try something very similar in VB .NET, it doesn't work!

--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

The squiggly line under N is a signal that you have a syntax error and can't even compile the program. The reason is in the box near the N.

The intent of this change is to allow you to "tune" your program by restricting the scope of a variable only needed in a block to just that block.

But Microsoft's own example, 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 is an interesting consequences to this. The scope of the variable may be confined to 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
Next

Output:

Value of N: 0
Value of N: 1
Value of N: 3
Value of N: 6
Value of N: 7
Value of N: 9

As you can see, N retains its value between executions of the inner loop. It's something to be aware of!

  1. About.com
  2. Technology
  3. Visual Basic
  4. Using VB.NET
  5. VB.NET Adds Block Level Scope

©2014 About.com. All rights reserved.