Welcome to NeoTekSystems Blog Sign in | Join | Help

For each loop gotcha

Take the following code:

Dim ar As ArrayList = New ArrayList

ar.Add(1)

ar.Add(2)

ar.Add(3)

For Each o As Object In ar

Dim total As Double

total += 2

MessageBox.Show(total.ToString)

Next

 

The compiler actually moves the dim statement out of the loop so you get output of 2, 4 and 6 as the loop goes through. 

This doesn't happen in c# as the compiler won't allow you to use double total;  It forces you to write double total = 0; which fixes the problem.  You could also add a total = 0 after the message box line to fix it.

 

Published Friday, September 09, 2005 4:55 PM by jspano

Comments

No Comments
Anonymous comments are disabled