1. 程式人生 > >Why does a 'for' loop behave differently when migrating VB.NET code to C#?

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

Because the for in VB is a different semantic than the for in C# (or any other C-like language)

In VB, the for statement is specifically incrementing a counter from one value to another.

In C, C++, C#, etc., the for statement simply evaluates three expressions:

  • The first expression is customarily an initialization
  • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met
  • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration

In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.

So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.