Chapter 2: Learning Just Enough C# or VB.NET: Basic Syntax | 59 |
As shown in Figure
In C#, the else statement snippet is similar to if. Type else and press TAB,
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