views:

37

answers:

3

I have a code structure something like this:

For row = 1 To numRows
   Dim arrayIndex As Integer = 0
   For column As Integer = startColumn To endColumn
      ' whatever code
      arrayIndex = arrayIndex + 1
   Next
Next

Dim arrayIndex As Integer = 0
For column As Integer = startColumn To endColumn
   ' whatever code
   arrayIndex = arrayIndex + 1
Next

Not exactly the code, so I don't really need suggestions about refactoring, but my problem is this - with this code I get a compiler error for the first Dim arrayIndex As Integer = 0 - "Variable 'arrayIndex' hides a variable in an enclosing block." As far as I can tell, arrayIndex is local to the first for loop and shouldn't exist by the time we reach the second loop. If I try to change the second declaration of arrayIndex to arrayIndex = 0, I get the error "Name 'arrayIndex' is not declared", as I expected. So is it visible, or not? Does this have something to do with the Dim keyword? Any suggestions of how to get around this, other than naming the second index variable something else?

+2  A: 

So is it visible, or not?

The other way round. The outer variable is visible in the inner scope. It cannot be accessed because it has not yet been declared and hence its lifetime has not yet started. But the name already exists in the scope.

Does this have something to do with the Dim keyword?

Not really, it is just a limitation of how scopes work in VB. A variable exists in scope even before its lifetime started. Since its name is carried over to nested scopes, no other variable there can have the same name.

Konrad Rudolph
So the second variable is in the outer scope, and so exists retroactively, in the earlier code? But can't actually be used retroactively?
froadie
A method cannot declare two variables with the same name even if they're not in the same scope. Well, generally at least. There's some wiggle room with For loops actually.
Chris Haas
+2  A: 

Why not just move it outside the loop and reset it after the first [one] ?

shadeMe
Thanks, I did think of this, it's just that the code is really much longer and I wanted to declare it right where I use it if possible. But this is probably what I'll end up doing.
froadie
@froadie: That’s not actually a good solution. Avoid reusing variables, that’s just unreadable because it gives the reader inaccurate semantic operations (namely, that the two uses of the variable are somehow connected). Either split the method into two separate ones, or use two distinct variable names in this case.
Konrad Rudolph
+1  A: 

Just like @shadeMe said, DIM it outside, assign it inside

Dim arrayIndex As Integer
For row = 1 To numRows
   arrayIndex = 0
   For column As Integer = startColumn To endColumn
      ' whatever code
      arrayIndex = arrayIndex + 1
   Next
Next

arrayIndex = 0
For column As Integer = startColumn To endColumn
   ' whatever code
   arrayIndex = arrayIndex + 1
Next
Chris Haas