Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

for (C# Reference)

The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is handy for iterating over arrays and for sequential processing. In the following example, the value of int i is written to the console and i is incremented each time through the loop by 1.

// statements_for.cs
// for loop
using System;
class ForLoopTest 
    static void Main() 
        for (int i = 1; i <= 5; i++)


The for statement executes the enclosed statement or statements repeatedly as follows:

  • First, the initial value of the variable i is evaluated.

  • Then, while the value of i is less than or equal to 5, the condition evaluates to true, the Console.WriteLine statement is executed and i is reevaluated.

  • When i is greater than 5, the condition becomes false and control is transferred outside the loop.

Because the test of conditional expression takes place before the execution of the loop, therefore, a for statement executes zero or more times.

All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:

        for (;;)
    // ...

For more information, see the following sections in the C# Language Specification:

  • For statements

  • 8.8.3 The for statement

© 2015 Microsoft