[{"data":1,"prerenderedAt":80},["ShallowReactive",2],{"/2025/12/14-vb.net-variable-value-in-loop":3},{"id":4,"title":5,"body":6,"date":71,"description":49,"extension":72,"meta":73,"navigation":74,"path":75,"robots":76,"seo":77,"stem":78,"__hash__":79},"posts/2025/12/14 VB.NET-variable-value-in-loop.md","14 VBNET Variable Value In Loop",{"type":7,"value":8,"toc":68},"minimark",[9,18,25,28,31,33,36,50,52,55,57,60],[10,11,13],"post-title",{":date":12},"date",[14,15,17],"h1",{"id":16},"vbnet-variable-value-in-loop","VB.NET Variable Value in Loop",[19,20,21],"notes",{},[22,23,24],"p",{},"This is a repost from my old blog. First posted in 8/17/2020.",[26,27],"br",{},[22,29,30],{},"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.",[26,32],{},[22,34,35],{},"For example, I have the following loop:",[37,38,39],"code-block",{},[40,41,46],"pre",{"className":42,"code":44,"language":45},[43],"language-text","For i = 0 to Count - 1\n   Dim x As Integer\n   x += 1\nNext\n","text",[47,48,44],"code",{"__ignoreMap":49},"",[26,51],{},[22,53,54],{},"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.",[26,56],{},[22,58,59],{},"Remember to initialize the variable when it is inside a loop, thus the above loop becomes:",[37,61,62],{},[40,63,66],{"className":64,"code":65,"language":45},[43],"For i = 0 to Count - 1\n   Dim x As Integer = 0\n   x += 1\nNext\n",[47,67,65],{"__ignoreMap":49},{"title":49,"searchDepth":69,"depth":69,"links":70},2,[],"2025-12-14T00:00:00.000Z","md",{},true,"/2025/12/14-vb.net-variable-value-in-loop",null,{"title":5,"description":49},"2025/12/14 VB.NET-variable-value-in-loop","WY3Hbapx8A1igp34BDFozuSd4QIpz3ymA57XAlRCLls",1785167452186]