开发者

Do .. While loop in C#?

How do I write a Do .. While loop in C#?

(Edit: I am a VB.NET programmer trying to make the move to C#, 开发者_JAVA百科so I do have experience with .NET / VB syntax. Thanks!)


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.


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!


//remember, do loop will always execute at least once, a while loop may not execute at all
//because the condition is at the top
do
{
  //statements to be repeated
} while (condition);


Quite surprising that no one has mentioned yet the classical example for the do..while construct. Do..while is the way to go when you want to run some code, check or verify something (normally depending on what happened during the execution of that code), and if you don't like the result, start over again. This is exactly what you need when you want some user input that fits some constraints:

bool CheckInput(string input) { ... }
...
string input;
...
do {
  input=Console.ReadLine();
} while(!CheckInput(input));

That's quite a generic form: when the condition is simple enough, it's common to place it directly on the loop construct (inside the brackets after the "while" keyword), rather than having a method to compute it.

The key concepts in this usage are that you have to request the user input at least once (in the best case, the user will get it right at the first try); and that the condition doesn't really make much sense until the body has executed at least once. Each of these are good hints that do..while is the tool for the job, both of them together are almost a guarantee.


Here's a simple example that will print some numbers:

int i = 0;

do {
  Console.WriteLine(++i);
} while (i < 10);


using System;

class MainClass
{
    public static void Main()
    {
        int i = 0;
        do
        {
            Console.WriteLine("Number is {0}", i);
            i++;
        } while (i < 100);
    }
}

Another method would be

using System;

class MainClass
{
    public static void Main()
    {
        int i = 0;
        while(i <100)
        {
            Console.WriteLine("Number is {0}", i);
            i++;
        }
    }
}


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.


Apart from the Anthony Pegram's answer, you can use also the while loop, which checks the condition BEFORE getting into the loop

while (someCriteria)
{
    if (someCondition)
    {
        someCriteria = false;
        // or you can use break;
    }
    if (ignoreJustThisIteration)
    {
        continue;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜