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.

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.

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


Comments

Popular posts from this blog

Sentinel One Strikes Again. No internet connection. Uninstall Sentinel One Agent.

A2 Hosting Let's Encrypt Can't Install Certificate on ASP.NET Core Application

NuGet Package Reference NU6105 Publish Error