Chapter 2: Learning Just Enough C# or VB.NET: Basic Syntax

63

and hold objects in memory in different forms, which could be Stack, List, Queue, and more. Here’s an example that loops on an array of strings:

C#:

string[] people = { "Megan", "Joe", "Silvia" };

foreach (var person in people)

{

Console.WriteLine(person);

}

VB:

Dim people = {"Megan", "Joe", "Silvia"}

For Each person As String In people

Console.WriteLine(person)

Next

In this example, people is an array of strings that contains three specific strings of text. The block of the loop will execute three times, once for each item in the array. Each iteration through the loop assigns the current name to person.

The For Each Loop Snippet

To add code using a for each snippet in C#, type fore and press TAB, TAB, which results in the snippet template shown in Figure 2-17.

The for each loop snippet gives you three fields to complete. The var is an implicit type specifier that allows you to avoid specifying the type of item; the compiler figures that out for you, saving you from some keystrokes. The item field will be a collection element type. You may leave var as is or provide an explicit type, which would be string in this case. You can tab through the fields to add meaningful identifiers for the item and collection you need to iterate through.

To execute the VB For Each snippet, type ?, TAB, C, ENTER, C, ENTER, f, ENTER and you’ll see the For Each loop template shown in Figure 2-18.

Figure 2-17 The C# for each loop snippet template

Page 86
Image 86
Microsoft 9GD00001 manual For Each Loop Snippet, The C# for each loop snippet template