Why does for loop behave differently when migrating VB.NET code to C#?

  • A+
Category:Languages

I'm in the process of migrating a project from VB to C# and I've had to change how a for loop being used is declared.

In VB.NET the for loop is declared below:

Dim stringValue As String = "42"  For i As Integer = 1 To 10 - stringValue.Length    stringValue = stringValue & " " + CStr(i)    Console.WriteLine(stringValue)                 Next 

Which outputs:

42 1 42 1 2 42 1 2 3 42 1 2 3 4 42 1 2 3 4 5 42 1 2 3 4 5 6 42 1 2 3 4 5 6 7 42 1 2 3 4 5 6 7 8 

In C# the for loop is declared below:

string stringValue = "42";  for (int i = 1; i <= 10 - stringValue.Length; i ++)  {    stringValue = stringValue + " " + i.ToString();    Console.WriteLine(stringValue); } 

And the output:

42 1 42 1 2 42 1 2 3 

This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.

Please see the code below:

string stringValue = "42"; int stringValueLength = stringValue.Length;  for (int i = 1; i <= 10 - stringValueLength; i ++)  {    stringValue = stringValue + " " + i.ToString();    Console.WriteLine(stringValue); } 

And the output:

42 1 42 1 2 42 1 2 3 42 1 2 3 4 42 1 2 3 4 5 42 1 2 3 4 5 6 42 1 2 3 4 5 6 7 42 1 2 3 4 5 6 7 8 

Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs, why is this?

 


In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.

So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.

In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: