Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The for loop in C# is an iteration statement that repeatedly executes a block of code as long as a specified boolean expression evaluates to true. It structurally consolidates the initialization, condition evaluation, and iteration operations into a single control header, dictating the exact lifecycle of the loop’s execution flow.
for (initializer; condition; iterator)
{
    // Loop body
}

Structural Components

The for statement header consists of three distinct, optional sections separated by semicolons:
  1. Initializer: Executed exactly once before the loop begins. It can be a local variable declaration or a comma-separated list of statement expressions, which includes assignments to variables declared outside the loop, method invocations, or object instantiations. If local variables are declared inline within this section, they are lexically scoped to the for statement, meaning they are inaccessible outside the loop body, condition, or iterator.
  2. Condition: A boolean expression evaluated prior to every iteration, including the first. If the expression evaluates to true, the loop body executes. If it evaluates to false, execution halts, and control flow transfers to the first statement following the loop block.
  3. Iterator: A comma-separated list of statement expressions evaluated at the end of each iteration, immediately after the loop body completes. It is typically responsible for mutating the loop control variable(s) (e.g., incrementing i++ or decrementing i--) before the next condition evaluation.

Execution Flow

The internal mechanics of the for loop follow a strict, sequential pipeline:
  1. The initializer executes.
  2. The condition is evaluated. If false, the loop terminates immediately.
  3. The loop body executes.
  4. The iterator executes.
  5. Control flow returns to Step 2.

Closure Capture Semantics

A critical nuance of the for loop’s lexical scoping involves closure capture semantics. Variables declared in the initializer are scoped to the entire for statement, not to individual iterations. If an anonymous function (lambda expression or delegate) captures a for loop variable, it captures a reference to that single, shared variable. This contrasts with foreach loops in C# 5.0 and later, which scope their iteration variables per-iteration. Consequently, all closures created within a for loop share the exact same variable, and deferred execution of those closures will observe the variable’s final, mutated value.
Action[] actions = new Action[3];

for (int i = 0; i < 3; i++)
{
    // All closures capture the exact same 'i' variable
    actions[i] = () => Console.WriteLine(i); 
}

foreach (var action in actions)
{
    action(); // Outputs 3, 3, 3 (not 0, 1, 2)
}
To capture the value of a specific iteration, the loop variable must be assigned to a locally scoped variable declared strictly within the loop body before being captured by the closure.

Syntax Variations and Technical Nuances

Multiple Expressions The initializer and iterator sections can process multiple comma-separated expressions. When declaring local variables inline within the initializer, all variables must share the same type. However, developers can initialize multiple variables of different types in the initializer section if those variables are declared outside the loop, by using a comma-separated list of assignment expressions.
// Inline declaration: variables must be of the same type
for (int i = 0, j = 10; i < j; i++, j--)
{
    // Both i and j are mutated in the iterator section
}

// External declaration: variables can be of different types
int index;
string status;

for (index = 0, status = "Active"; index < 5; index++)
{
    // Executes using externally scoped variables
}
Optional Sections Every section within the for header is optional. Omitting the condition implicitly evaluates to true, resulting in an indefinite loop unless a control transfer statement is encountered within the body.
int counter = 0;

for (;;) 
{
    // Indefinite loop structure
    counter++;
    if (counter > 10) break;
}
Control Transfer Statements The linear execution of a for loop can be interrupted from within the body using jump statements:
  • break: Immediately terminates the loop entirely, transferring control to the statement following the loop.
  • continue: Bypasses any remaining statements in the current iteration’s body and jumps directly to the iterator evaluation, followed by the condition evaluation for the next cycle.
for (int i = 0; i < 10; i++)
{
    if (i % 2 == 0)
    {
        continue; // Skips the rest of the body, jumps to i++
    }
    
    if (i == 7)
    {
        break; // Terminates the loop entirely
    }
}
Master C# with Deep Grasping Methodology!Learn More