I'm in the process of migrating a project from Visual Basic 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 Visual Basic differs to C# in terms of Visual Basic 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?
Arrays in particular should be just as fast under foreach, but for everything else, plain loops are faster.
The while loop initially checks the defined condition, if the condition becomes true, the while loop's statement is executed. Whereas in the Do loop, is opposite of the while loop, it means that it executes the Do statements, and then it checks the condition.
You use a For ... Next structure when you want to repeat a set of statements a set number of times. In the following example, the index variable starts with a value of 1 and is incremented with each iteration of the loop, ending after the value of index reaches 5.
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#.
The end condition evaluation in C# has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With