| You are here: | About>Computing & Technology>Visual Basic> Using VB.NET> VB.NET Adds Block Level Scope |
![]() | Visual Basic |
VB.NET Adds Block Level ScopeDec 30 2007 VB.NET gives you another code optimization choice!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: -------- 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! -------- 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 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 Output: Value of N: 0 As you can see, N retains its value between executions of the inner loop. It's something to be aware of! |
Las Vegas on a BudgetFind a BargainHotel DealsCheap EatsFree AttractionsEntertainment for Less |
All Topics | Email Article | | | ![]() |
| Advertising Info | News & Events | Work at About | SiteMap | Reprints | Help | Our Story | Be a Guide |
| User Agreement | Ethics Policy | Patent Info. | Privacy Policy | ©2008 About, Inc., A part of The New York Times Company. All rights reserved. |


