By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,184 Members | 1,162 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,184 IT Pros & Developers. It's quick & easy.

block level variables .. when to use them and why??

P: n/a
Hi All,

As you all know in vb.net we can declare block level
variables. Like :
Dim I As Integer
For I = 1 To 3
Dim N As Long
' N has block scope in VB.NET
N = N + I
Next

Can someone tell me what is the benefit of
doing so ..

Which practice is better ..
1. declaring variables at the top of the function/procedure
2. declaring variables whereever needed

Thanx

Regards,
Anoj Kumar

Nov 21 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
CT
Anoj,

The benefit of using block scoped variables is that they go out of scope
once your code exits the block of code in question. I personally think that
makes your code easier to read. Now, you were giving an example with a For
Next loop, but IMO anything is "block scoped" meaning that a variable in a
procedure is local to that procedure. So, with that in mind I think your
code looks cleaner if you declare your variables at the top of the block.

BTW, I has procedure level scope in your example and that is probably your
intention, but if it's only needed as a loop counter, you might consider
this approach:

For I As Integer = 1 To 3
--
Carsten Thomsen
Enterprise Development with VS .NET, UML, AND MSF
http://www.apress.com/book/bookDisplay.html?bID=105

"Anoj" <su********@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Hi All,

As you all know in vb.net we can declare block level
variables. Like :
Dim I As Integer
For I = 1 To 3
Dim N As Long
' N has block scope in VB.NET
N = N + I
Next

Can someone tell me what is the benefit of
doing so ..

Which practice is better ..
1. declaring variables at the top of the function/procedure
2. declaring variables whereever needed

Thanx

Regards,
Anoj Kumar

Nov 21 '05 #2

P: n/a
Anoj,

As attention on CT message,
For i as Integer = 0 to x
Is only working on VBNet newer than 2002.

Just an addition.
The rest I agree complete.

Cor
Nov 21 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.