64Microsoft Visual Studio 2010: A Beginner’s Guide

Figure 2-18 The VB For Each loop snippet template

While Loops

A while loop will allow a block of code to execute as long as a specified condition is true. Here’s an example that does a countdown of numbers:

C#:

int count = 3;

while (count > 0)

{

Console.WriteLine("count: " + count); count--;

}

VB:

Dim count As Integer = 3

While count > 0 Console.WriteLine("count: " & count) count -= 1

End While

The while loop executes as long as count is greater than 0. Since count is 3 and will decrement by one each time through the loop, the value will change from 3 to 2 to 1 and then the loop won’t execute anymore. Be careful not to create endless loops.

The while Loop Snippet

To create a while loop snippet, type wh and press TAB, TAB; and you’ll see the snippet template in Figure 2-19 (C#) or Figure 2-20 (VB).

For C#, filling in the condition and pressing ENTER places the carat inside the while loop block.

Figure 2-19 The C# while loop snippet template

Page 87
Image 87
Microsoft 9GD00001 manual While Loops, While Loop Snippet