Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do .. While loop in C#?

Tags:

c#

loops

do-while

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

like image 683
Srikrishna Sallam Avatar asked Sep 05 '25 03:09

Srikrishna Sallam


2 Answers

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.

like image 159
Jon Skeet Avatar answered Sep 07 '25 21:09

Jon Skeet


Since you mentioned you were coming from VB.NET, I would strongly suggest checking out this link to show the comparisons. You can also use this wensite to convert VB to C# and vice versa - so you can play with your existing VB code and see what it looks like in C#, including loops and anything else under the son..

To answer the loop question, you simple want to do something like:

while(condition)
{
   DoSomething();
}

You can also do - while like this:

do
{
   Something();
}
while(condition);

Here's another code translator I've used with success, and another great C#->VB comparison website. Good Luck!

like image 31
dferraro Avatar answered Sep 07 '25 23:09

dferraro