Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 2: Learning Just Enough C# or VB.NET: Basic Syntax 65
Do Loops
You can use a do loop if you want the code in the loop to execute at least one time. Here’s
an example that demonstrates a simple menu that obtains user input:
C#:
string response = "";
do
{
Console.Write("Press 'Q' and Enter to break: ");
response = Console.ReadLine();
} while (response != "Q");
VB:
Do
Console.Write("Press Q and Enter to break: ")
response = Console.ReadLine()
Loop While response <> "Q"
In this example, you’ll always get the prompt for Press ‘Q’ and Enter to break:. The
Console.ReadLine reads the user input, which is of type string. If the input is a string that
contains only a capital Q, the loop will end.
VB has another variation of loops that use the Until keyword, as follows:
Do
Console.Write("Press Q and Enter to break: ")
response = Console.ReadLine()
Loop Until response = "Q"
In this code, you can see that the Until condition will continue looping while the
condition is not true, which is opposite of the Do Loop While.
The Do Loop Snippet
To use the do loop snippet, type do and press TAB, TAB; you’ll see the do loop template
shown in Figure 2-21.
Figure 2-20 The VB while loop snippet template
Figure 2-21 The C# do loop snippet template