The for Statement

Besides a condition and a body, lots of loops require an initialization phase as a preamble to the execution of the loop. In addition to this, it’s common to have an update phase that gets executed at the end of each iteration. The for statement is what enables cleaner syntax for this scenario:

for (initializer; condition; iterator)    embedded-statement

As usual, the embedded statement has an optional pair of curly braces surrounding it. (The usual remarks apply.)

The for statement can be seen as shorthand syntax for the following equivalent while statement:

{    initializer;    while (condition)    {        embedded-statement;        iterator;    }}

Notice the outer pair of curly braces establishing a scope for variables that ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.