C#

C# Fundamentals

19 lessons

Progress0%
1. Introduction to C#
1What is C#?
2. Variables and Data Types
1Data Types in C#
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsOptional Parameters and Overloading
5. Object-Oriented Programming
Classes and PropertiesInheritanceInterfaces and Generics
6. LINQ and Async
LINQ Queriesasync/await
7. Exception Handling
try/catch/finally & Exception TypesCustom Exceptions & IDisposable
8. Delegates & Events
Delegates & LambdaEvents & Event Handlers
9. Records & Pattern Matching
Record TypesPattern Matching & Switch Expressions
10. File I/O & JSON
File & Stream OperationsJSON Serialization
All Tutorials
C#Control Flow
Lesson 4 of 19 min
Chapter 3 · Lesson 2

Loops

Loops in C#

C# supports all common loop patterns.

for loop Index-based repetition:

csharp
for (int i = 0; i < 10; i++) { … }

foreach loop Iterates any IEnumerable<T> without managing an index:

csharp
foreach (var item in collection) { … }

while loop Condition checked before each iteration:

csharp
while (condition) { … }

do-while loop Body runs at least once:

csharp
do { … } while (condition);

break and continue

  • break exits the nearest loop.
  • continue skips the remaining body and moves to the next iteration.

Key points:

  • Prefer foreach over for when the index is not needed — it works with all collections.
  • C# foreach uses the iterator pattern internally — never modify the collection inside a foreach.
  • LINQ Where/Select can often replace imperative loops for concise transformations.

Code Examples

for, while, do-whilecsharp
using System;
class LoopDemo {
    static void Main() {
        // for
        int sum = 0;
        for (int i = 1; i <= 5; i++) sum += i;
        Console.WriteLine($"Sum: {sum}");

        // while — find first power of 2 >= 100
        int n = 1;
        while (n < 100) n *= 2;
        Console.WriteLine($"First power of 2 >= 100: {n}");

        // do-while
        int x = 1;
        do {
            Console.Write(x + " ");
            x *= 2;
        } while (x <= 8);
        Console.WriteLine();
    }
}

do-while guarantees at least one execution. while may not execute at all if the condition is initially false.

foreach with break and continuecsharp
using System;
class ForeachDemo {
    static void Main() {
        string[] words = { "apple", "banana", "cherry", "date", "elderberry" };

        Console.WriteLine("Words not starting with 'b':");
        foreach (var word in words) {
            if (word.StartsWith("b")) continue;
            Console.WriteLine($"  {word}");
        }

        Console.WriteLine("First word longer than 5 chars:");
        foreach (var word in words) {
            if (word.Length > 5) {
                Console.WriteLine($"  {word}");
                break;
            }
        }
    }
}

continue skips to the next element; break exits the entire loop. foreach works on any IEnumerable<T>.

Quick Quiz

1. Which C# loop is best when you need the index during iteration?

2. What happens if you modify a list inside a foreach loop?

Was this lesson helpful?

PreviousNext