Do .. While loop in C#?

Srikrishna Sallam picture Srikrishna Sallam · Mar 29, 2010 · Viewed 58.3k times · Source

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!)

Answer

Jon Skeet picture Jon Skeet · Mar 29, 2010

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.