DEV Community


The four different loops of C#

jos512 profile image Jos Originally published at ・10 min read

This article appeared earlier on my website. It's also my first article here on! :-)

To repeat code in C# we can use four different loops. But what loops are there and how do we use them? Let's find out.

Looping in C# programs: four different options

A loop repeats the same code several times. They make calculations and processing elements in a collection possible. Together with if statements they're an essential feature to control how our program executes.

Not every situation requires the same loop. And so C# has several loop options:

  • The for loop, which counts from one value to another.
  • The foreach loop, that easily iterates over all elements in a collection.
  • The while loop, which goes on as long as some condition is true.
  • And the do-while loop, which always executes at least once.

Let's take a closer look at these loop types.

Make a counting loop: C#'s forloop

The for loop repeats code up to a certain number of times. That behaviour is possible because this loop counts from one value to the next. This way we perform calculations and loop over a list or array.

The for loop is also a compact loop. It combines three common loop actions together: declare and initialise the loop variable, check the loop condition before each loop cycle, and update the loop variable after each iteration.

Quick example: the forloop in C

Here's how C#'s for loop looks:

    for (int i = 0; i < 5; i++)
        Console.Write(i + "  ");

The header of this for loop has three parts:

  • First we declare and initialise the i loop variable to a value of 0.
  • The loop condition checks if the i variable is under (<) 5. When it is, code inside the loop executes. When the condition tests false, the loop ends.
  • The last part updates the i loop variable with one after each loop cycle (i++). This way we iterate from one value to the next.

See C#'s for loop explained for much more. There's also an article about alternative for loops in C#.

When to use the forloop?

These are the situations in which we can use a for loop:

  • When code needs to execute a specific number of times. Since for automatically creates and updates the loop variable, it's easier to work with than other loops in those situations.
  • When code inside the loop needs a counting variable. Other C# loops can also use a counting variable, but the for loop manages one for us.
  • When code should not execute more than a certain number of times. In those cases for can easily count towards those loop limits.

Strengths and weaknesses of C#'s forloop

These are the strengths of C#'s for loop:

  • A for loop makes it easy to modify a collection or examine adjacent (the next or previous) elements.
  • Once we make the for loop header, we can focus on code inside the loop. There's no need to manage the loop variable inside the loop.
  • A for loop combines making a loop variable, updating that loop variable, and evaluating the loop's condition into a single line. This makes for a compact loop.
  • The for loop header always changes the loop variable after each loop cycle. There's no risk that we accidentally jump over the code that changes that variable with the continue statement.

The for loop also has some weaknesses:

  • If all we need is to loop over a collection, the for loop is more complex than needed. A foreach loop is then easier to work with.
  • Not every expression can be used in the for loop header to change the loop variable. If we need to change that variable in complex ways, the code for that has to be placed inside the loop.

Easily loop through a collection: C#'s foreachloop

The foreach loop elegantly loops through all items in a collection. The key feature of foreach is its loop variable. That variable is set to an element from the collection we loop over during each loop cycle.

Inside the loop we use that variable to work with the element's value. Then after each loop cycle, C# automatically sets that variable to the value of the next element in the collection. This makes foreach a lot easier to work with than C#'s other loops.

Quick example: the foreachloop

Here's how C#'s foreach loop looks:

    int[] values = { 0, 1, 2, 3, 4 };

    foreach (int value in values)
        Console.Write(value + " ");

The header of each foreach loop has three components:

  • First we define the type of loop variable. The loop above uses int because the array we loop over contains integer values.
  • Then we name the local loop variable. We use value in the above loop. In the loop's body, that variable refers to the element we currently loop over.
  • With the in keyword we specify the collection of values to loop over. We use values here, which is the integer array that's defined just above the loop.

See C#'s foreach loop explained for more details.

When to use the foreachloop?

We use C#'s foreach loop to work with each value from a collection. For that purpose foreach is a more convenient alternative to the for loop.

foreach cannot change the value it loops over. Or only iterate through part of the collection. For those two scenarios we still use the for loop.

Strengths and weaknesses of the foreachloop

Here are some advantages of the foreach loop:

  • It's an easy loop to write; C# automatically manages the loop variable and sets it to an element during each loop cycle. That makes the loop easier to write but also reduces possible mistakes.
  • foreach automatically goes through all elements in a collection. There's no need to manage the loop's start and end index.

Here are some foreach disadvantages:

  • Because the foreach loop works with a copy of the element we loop over (rather than the actual element), we cannot make changes to the collection we loop over. To make those changes we need to use a for loop, while loop, or do-while loop instead.
  • A foreach loop always goes through an entire collection. To process only a part, or skip certain elements, we can make a new collection or use the for loop.
  • A foreach loop always loops from index 0 to index Length - 1 (or Count - 1). If the loop should iterate backward, it's easier to use a for loop instead.
  • When our code also has to work with the element's index (besides its value), then the for loop is an easier choice.

Loop as long as something is true: the whileloop

The while loop executes code for as long as some Boolean condition tests true. When that condition becomes false, the loop ends.

The strength of while is that we don't need to know in advance how many loop cycles we need. Instead the loop simply goes on for as long as its condition tests true. We do need some code inside the loop to make that condition false at some point; otherwise, the loop keeps running.

Quick example: C#'s whileloop

Here's how C#'s while loop looks like:

    int i = 0;
    while (i < 5)
        Console.Write(i + " ");

Before the loop we first make our i integer variable with a value of 0. Then the while loop begins. Its condition checks if that variable is under (<) 5. When it is, code inside the loop executes.

That code also increases the value of i with 1 (i++). That makes the loop's condition (i < 5) false after 5 loop cycles. (The alternative is that we get stuck with an infinite loop that doesn't end.)

See C#'s while loop explained to learn more.

When to use the whileloop?

We use the while loop when we have to repeat code several times, but don't know how many loop cycles we need. This for instance happens when we process user input or crawl a website. In those situations we might need 10 loop cycles or 450 iterations. With a while loop we simply continue until some condition turns up false.

Another use case are complex calculations that don't involve the basic counting that the for loop provides.

Sometimes we also use the while loop to deliberately make an infinite loop. That way we can have our program 'wait' on certain things, like incoming data. In those cases while keeps our program active and ready.

If we have to loop over values of a collection, then it's often easier to use the foreach loop. And looping from one numerical value to another is easier with the for loop.

Strengths and weaknesses of the whileloop

These things the while loop does well:

  • The while loop is an intuitive loop that's easy to read and understand. It's also a common loop, so many programmers understand your code when you use while.
  • The while loop continues until its condition tests false. That helps when we don't know the number of loop cycles in advance.
  • We can often update the loop variable inside the while loop header for details). That makes the loop's body more compact.

Here are some weaknesses that the while loop has:

  • The while loop often needs a statement inside its loop body that changes the loop condition. That means extra code. Plus code that we can easily skip over by accident with the continue statement.
  • The while loop is cumbersome when we need to count values or process collections. The for loop is an easier loop in those cases.

Execute once, then run while true: the do-whileloop

A less common iteration option is C#'s do-while loop. This loop repeats code for as long as a condition tests true. That's similar to the while loop. But here's what makes do-while unique: this loop evaluates its condition after the loop's body executed.

Since that test happens after the loop's code, code inside the loop always runs at least once. If the loop condition is true after that first run, the do-while loop continues. Else it stops. So there's at least one loop cycle, with the possibility of getting more.

Quick example: the do-whileloop in C

Here's a quick example of the do-while loop:

    int i = 0;
        Console.Write(i + " ");
    } while (i < 5);

We first declare the i variable and give it a default of 0. Then we make a do-while loop. First we use the do keyword and then a pair of braces ({ and }). Between them we place our code that should repeatedly execute.

The loop's body has the Console.Write() method output the current value of i. Then the increment operator (++) increases that loop variable with one. That makes the loop condition false at some point.

Then we check that loop condition. We use the while keyword and evaluate whether i is less than (<) 5. As long as it is, code inside this loop executes.

See C#'s do-while loop explained to learn more.

When to use C#'s do-whileloop?

In general, the do-while loop can handle the same situations as the while loop can. That is, we use do-while to loop for as long as some condition remains true, without necessarily knowing in advance how many loop cycles that takes.

Of course what makes the do-while loop unique is that it always executes once. But because do-while is rather uncommon, chances are that people reading your code find this loop harder to understand. Because of that it's a good idea to use do-while only when you definitely need its unique feature.

Strengths and weaknesses of the do-whileloop

These are the strengths of the do-while loop:

  • do-while always executes its loop body once. This way other program can safely assume that the loop's code executed.
  • Like the while loop, do-while loop runs for as long as its condition tests true. This makes the loop flexible without us specifying in advance how many loop cycles we need.

There are some disadvantages with the do-while loop too:

  • When we count with the do-while loop, we'll have to use a separate variable to control the loop. We have to manage that variable inside the loop in the right way, and not for instance jump over it with the continue statement. This requires a bit more work than the same behaviour with the for loop, for instance.
  • The do-while loop is uncommon. That makes mistakes more likely. And increases the odds that people reading your code have trouble understanding the loop well.
  • The do-while loop is cumbersome when we need to process elements in a collection. For that the foreach loop or the for loop are much better options.
  • A do-while loop guarantees that the loop's code always runs once. But that's also possible with a regular while loop that has its loop condition initialised to true.


C# has four types. With the for loop we count from one value to another. This helps when we process elements in a collection and with math.

The foreach loop can also iterate through a collection. This loop is however easier to manage, automatically goes through an entire collection, and updates the loop variable automatically.

If we need to repeat code but don't know how many loop cycles that takes, we use the while loop. Before each loop cycle, while checks a true/false condition. When true, the loop runs; else, the loop ends (or doesn't even start).

Similar is the do-while loop. This loop also keeps running when a condition tests true. What's unique, however, is that do-while always executes once, even when its condition is false the first time.


Editor guide