How to solve this problem in VB.NET?

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 really a code, so I don’t need refactoring suggestions, but my problem is with this code I get a compiler error for the first Dim arrayIndex As Integer = 0 - β€œVariable” arrayIndex 'hides the variable in the enclosing block. "As far as I can tell , arrayIndex is local to the first for loop and should not exist by the time the second loop is reached. If I try to change the second declaration of arrayIndex to arrayIndex = 0 , I get the error "The name" arrayIndex "is not declared", as I expected. So it can be seen or not? Is this related to the Dim keyword? Any suggestions on that How to get around this, differing from the name of the second index variable something else?

+4
source share
3 answers

So is it visible or not?

And vice versa. An external variable is visible in the internal area. Access to it is unavailable because it has not yet been announced and, therefore, its service life has not yet begun. But the name already exists in the area.

Is this related to the Dim keyword?

Not really, it's just a limitation on how areas work in VB. A variable exists in the realm of visibility even before the beginning of its life. Since its name is transferred to nested areas, no other variable can have the same name.

+3
source

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

+2
source

Just as @shadeMe said: DIM is 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 
+1
source

Source: https://habr.com/ru/post/1307147/


All Articles