How do I write a Do .. While loop in C#?
(Edit: I am a VB.NET programmer trying to make the move to C#, so I do have experience with .NET / VB syntax. Thanks!)
The answer by Jon Skeet is correct and great, though I would like to give an example for those unfamiliar with while
and do-while
in c#:
int i=0;
while(i<10)
{
Console.WriteLine("Number is {0}", i);
i++;
}
and:
int i=0;
do
{
Console.WriteLine("Number is {0}", i);
i++;
}while(i<10)
will both output:
Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9
as we would expect. However it is important to understand that the do-while loop always executes the body the first time regardless of the check. This means that if we change i's starting value to 100 we will see very different outputs.
int i=100;
while(i<10)
{
Console.WriteLine("Number is {0}", i);
i++;
}
and:
int i=100;
do
{
Console.WriteLine("Number is {0}", i);
i++;
}while(i<10)
Now the while loop actually generates no output:
however the do-while loop generates this:
Number is 100
despite being well over 10. This is because of the unique behavior of a do-while loop to always run once unlike a regular while loop.
The general form is:
do
{
// Body
} while (condition);
Where condition
is some expression of type bool
.
Personally I rarely write do/while loops - for
, foreach
and straight while
loops are much more common in my experience. The latter is:
while (condition)
{
// body
}
The difference between while
and do...while
is that in the first case the body will never be executed if the condition is false to start with - whereas in the latter case it's always executed once before the condition is ever evaluated.