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

  • Thread starter Thread starter Anoj
  • Start date Start date
A

Anoj

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
 
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
 
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
 
CT said:
So, with that in mind I think your code looks cleaner if you declare your
variables at the top of the block.

I think that decision should be based on personal preference. Variables can
be used only after their declaration, and thus additional scoping inside the
local scope is possible:

\\\

' Variable 'i' cannot be accessed.
....
Dim i As Integer

' Variable 'i' can be accessed.
///
 
Herfried,
I think that decision should be based on personal preference. Variables
can be used only after their declaration, and thus additional scoping
inside the local scope is possible:
And is CT allowed to have that?

:-)))

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top