开发者

How do I resolve this scope issue in VB .NET?

开发者 https://www.devze.com 2022-12-27 16:59 出处:网络
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

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 should开发者_Go百科n'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?


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号