Monday, August 17, 2020

VB.NET Variable Value in Loop

While troubleshooting other things, I found out that I got trapped in the beginner's mistake. Essentially, I'm expecting when I declare a variable inside a loop, it is automatically set to its default value for each loop, but it is not the case.

Problem

For example, I have the following loop:

For i = 0 to Count - 1
Dim x As Integer
x += 1
Next

I'm expecting the value of x to stay at 1 for each loop because I declare it inside the loop, but by the end of the second loop, the value of x is 2 and so on. Apparently, the variable is getting reused and the existing value is carried over to the next iteration.

Solution

Remember to initialize the variable when it is inside a loop, thus the above loop becomes:

For i = 0 to Count - 1
Dim x As Integer = 0
x += 1
Next


No comments:

Post a Comment