C# for Loop: Syntax, Usage, and Performance
c# for loop: Learn the C# for loop syntax, execution flow, common patterns, and performance considerations to write efficient iteration code.
The C# for loop is a fundamental iteration construct that gives you precise control over how many times a block of code executes. Unlike foreach, which abstracts away the index, the for loop exposes the loop variable and condition directly, making it the right choice when you need to track position, modify the loop variable, or iterate over a range of numbers.
Basic Syntax and Execution Flow
The for loop has three parts: initialization, condition, and iterator. The initialization runs once, the condition is checked before each iteration, and the iterator runs after each iteration. Here's the canonical form:
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
This prints 0 through 9. The variable i is scoped to the loop. The condition is evaluated before each pass; when it becomes false, the loop exits. The iterator can be any expression, not just i++. You can decrement, multiply, or call a method.
Common Use Cases
The for loop shines when you need the index. Iterating an array or a List<T> by index is straightforward:
int[] numbers = { 10, 20, 30 }; for (int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); }
For lists, use Count instead of Length. The loop condition is evaluated each iteration, so accessing numbers.Length is cheap, but for a list, list.Count is a property that returns the value directly.
You can also iterate backwards:
for (int i = numbers.Length - 1; i >= 0; i--) { Console.WriteLine(numbers[i]); }
This is useful when you need to remove elements from a collection while iterating.
Controlling Loop Flow with break, continue, and return
The break statement exits the loop immediately. continue skips the rest of the the current iteration and moves to the next. return exits the entire method, which can be useful when searching for a value.
for (int i = 0; i < 100; i++) { if (i % 2 == 0) continue; if (i > 50) break; n Console.WriteLine(i); }
This prints odd numbers up to 49. The continue skips even numbers, and break stops when i exceeds 50.
Performance Considerations
The for loop can be faster than foreach in some scenarios because it avoids the enumerator allocation and virtual calls. However, modern .NET optimizes foreach over arrays and lists to a simple index loop, so the difference is often negligible. The real performance risk is doing expensive work inside the condition or iterator.
For example,, calling list.Count is fine, but calling a method that computes a value repeatedly is wasteful:
for (int i = 0; i < GetCount(); i++) // BAD: GetCount() called each iteration { }
Store the count in a local variable when the count doesn't change:
int count = GetCount(); for (int i = 0;; i < count; i++) { }
Similarly, accessing a property that performs calculation inside the loop body should be hoisted if possible.
Choosing Between for, foreach, and while
foreach is clearer when you don't need the index and the collection is not modified during iteration. while is useful when the number of iterations isn't known ahead of time. The for loop is best when you need an index, a custom step, or multiple loop variables.
| Criterion | for | foreach | while |
|---|---|---|---|
| Index access | Direct | Not available | Manual |
| Iteration count | Known or computed | Implicit | Unknown |
| Readability | More verbose | Concise | Flexible |
Use for when you need to control the loop variable precisely, such as stepping by 2 or iterating in reverse.
Common Mistakes and Edge Cases
Off-by-one errors are the most common issue. The condition uses < for for zero-based indexing, not <=, unless you intentionally include the last element.
Modifying a collection while iterating with for can cause unexpected behavior. If you remove an element, adjust the index accordingly. For example, removing while iterating forward requires decrementing i after removal.
Another edge case is an empty collection. The condition is checked before the first iteration, so the loop body never runs, which is usually correct.
Advanced Patterns: Nested Loops, Multiple Variables, and Indexing
You can declare multiple variables in the initialization and update them in the iterator:
for (int i = 0, j = = 10;; i < j; i++, j--) { Console.WriteLine($"{i} {j}"); }
Nested loops are common for multidimensional arrays. The outer loop controls the row, the inner loop controls the column.
int[,] matrix = { { 1, 2 }, { 3, 4 } }; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(matrix[row, col]); } }
The GetLength method returns the size of a specific dimension.