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

59

As shown in Figure 2-11, the template brings you to a highlighted field for specifying the condition of the if statement. For C#, type the condition you want evaluated and press ENTER; the snippet completes by placing your carat within the if statement block. For VB, just place your cursor where you want to begin typing next.

In C#, the else statement snippet is similar to if. Type else and press TAB, TAB—the else template appears with the carat between the blocks of the else. There isn’t a VB else snippet; just type Else between the last statement of the If and the End If.

Switch/Select Statements

A switch statement (Select Case statement for VB) tells the computer to evaluate one or many conditions and branch appropriately. Here’s an example that will perform different actions depending on the value of a name variable:

C#:

var name = "Megan";

switch (name)

{

case "Joe":

Console.WriteLine("Name is Joe"); break;

case "Megan":

Console.WriteLine("Name is Megan"); break;

default:

Console.WriteLine("Unknown Name"); break;

}

VB:

Dim name As String = "Megan"

Select Case name

Case "Joe"

Console.WriteLine("Name is Joe")

Case "Megan"

Console.WriteLine("Name is Megan")

Case Else

Console.WriteLine("Unknown name")

End Select

In the C# example, you can see the keyword switch with the value being evaluated in parentheses. The code to execute will be based on which case statement matches the switch value. The default case executes when there isn’t a match. The break keyword

Page 82
Image 82
Microsoft 9GD00001 manual Switch/Select Statements