Do .. While loop in C#?

后端 未结 8 1192
后悔当初
后悔当初 2020-12-18 18:21

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

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 19:01

    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.

提交回复
热议问题