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

61

In C#, you normally just add the case statements you need. However, there is a special feature of the switch snippet that makes it even more efficient to use enums, creating a case for each enum value automatically. In the following example, we use the accountType variable of the enum type BankAccount from Listing 2-3. To see how the switch statement works with enums, type sw and press TAB, TAB ; you’ll see the switch template with the condition field highlighted. Type accountType in the field and press ENTER. The switch snippet will automatically generate cases for each of the BankAccount enum members as follows:

switch (accountType)

{

case BankAccount.Checking: break;

case BankAccount.Saving: break;

case BankAccount.Loan: break;

default:

break;

}

The enum comes through as a convenience that is easy to read and minimizes potential spelling mistakes when using strings. Now that you know how branching statements work, let’s move on to loops.

Loops

You can perform four different types of loops: for, for each, while, and do. The following sections explain how loops work.

For Loops

For loops allow you to specify the number of times to execute a block of statements. Here’s an example:

C#:

for (int i = 0; i < 3; i++)

{

Console.WriteLine("i = " + i);

}

VB:

For i As Integer = 0 To 2

Console.WriteLine("i = " & i)

Next

Page 84
Image 84
Microsoft 9GD00001 manual For Loops