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.

A while loop in C# is an entry-controlled iteration statement that repeatedly executes a block of code as long as a specified boolean expression evaluates to true. Because the condition is evaluated prior to the execution of the loop’s body, it is classified as a pre-test loop, meaning the enclosed statements may execute zero or more times.

Syntax

while (boolean_expression)
{
    // Statements to execute
}

Execution Mechanics

  1. Condition Evaluation: Control flow reaches the while statement and evaluates the boolean_expression. This expression must resolve to a bool data type.
  2. Execution: If the expression evaluates to true, the runtime enters the loop block and executes the statements sequentially.
  3. Iteration: Upon reaching the end of the block, control jumps back to the top of the loop to re-evaluate the boolean_expression.
  4. Termination: If the expression evaluates to false at any point during the condition check, the loop terminates immediately. Control is transferred to the first statement following the loop block.

Code Example

int counter = 0;

while (counter < 3)
{
    Console.WriteLine(counter);
    counter++; // Modifies the state evaluated in the condition
}

Control Transfer Statements

The standard execution flow of a while loop can be explicitly altered using jump statements:
  • break: Immediately terminates the entire loop. Control passes to the statement directly following the loop block, regardless of the boolean expression’s state.
  • continue: Immediately terminates the current iteration. Control jumps directly back to the boolean_expression evaluation, bypassing any remaining statements in the loop body for that specific iteration.

Technical Considerations

  • Infinite Loops: If the boolean_expression is statically true (e.g., while (true)) or if the state evaluated by the condition is never modified within the loop body, the loop will execute indefinitely until the process is terminated or a break statement is encountered.
  • Variable Scope: Variables declared within the while loop block are scoped locally to that block. They are created and destroyed on each iteration. Variables evaluated in the boolean_expression must be declared in an outer scope prior to the loop.
  • Single-Statement Body: If the loop body consists of only a single statement, the curly braces { } can be omitted, though retaining them is a standard convention for maintainability.
Master C# with Deep Grasping Methodology!Learn More