Loops are very common when you are programming. They are used to iterate through a list or array or run until a certain condition has been reached. There are different kinds of loops and this time I want to show you all about the while loop with C#.
Things you should know
For this tutorial you need to know or have the following terms/techniques:
- General C# and .NET knowledge
I am using .NET 6 for this tutorial. - Visual Studio 2022 or higher
Table Of Contents
What is the While loop?
The while loop is a loop that continues executing code until a certain condition has been met. It’s like a normal day-to-day thing: Keep drinking until you are not thirsty anymore. In this, the keep drinking is the execution, and the until not thirsty is the condition. The specified condition needs to be true.
The buildup of a while loop in C# is always the same:
- It starts with while
- Then you specify the condition
- You write the code to execute as long as the condition is true
- The execution of the code stops when the condition is false
It looks like a Do-While, but that will execute the code block at least once.
Code that is written below the while loop won’t be executed until the while loop is finished.
while(condition){
code...
}
Examples
Below are some examples that show how the while loop with C# works.
bool run = true;
int i = 0;
while(run)
{
Console.WriteLine("Executing...");
i++;
if(i > 10)
run = false // Run is set to false, to this will stop the While loop
}
Or shorter:
int i = 0;
while (i < 10)
{
i++;
}
Stopping / Break
In some cases, you might want to stop or abort the while loop before the condition is met. You can do this with break. In the example below, the while loop will stop as soon as i equals 5.
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
if (i == 5)
break;
i++;
}
Next iteration / Continue
In some cases, you want to skip some of the code and continue to the next run/iteration. This can be achieved by using the continue. In the example below, the number 5 won’t be printed on the console.
int i = 0;
while (i < 10)
{
i++;
if (i == 5)
continue;
Console.WriteLine(i);
}