#178 – Throwing an Exception from a switch Statement

Instead of a break statement as a terminator of a case clause in a switch statement, you can also throw an exception.

            switch (surname)       // surname is a string
            {
                case "Aarhus":
                case "Enevoldsen":
                    Console.WriteLine("Norwegian");
                    break;
                case "Brosnan":
                case "McGill":
                    Console.WriteLine("Irish");
                    throw new ApplicationException("Software doesn't work for Irish people");
                default:
                    Console.WriteLine("UNKNOWN origin");
                    break;
            }

#177 – Using goto in a switch Statement

You can use a goto statement within a switch statement to jump to another case clause.  This allows you to execute the contents of more than one case clause for a particular value of the switch expression.

            switch (day)
            {
                case DayOfWeek.Sunday:
                    Console.WriteLine("Go to church");
                    goto case DayOfWeek.Saturday;
                case DayOfWeek.Monday:
                    Console.WriteLine("Read Ulysses");
                    break;
                case DayOfWeek.Tuesday:
                    Console.WriteLine("Call Dad");
                    goto case DayOfWeek.Saturday;
                case DayOfWeek.Wednesday:
                    Console.WriteLine("Do laundry");
                    goto case DayOfWeek.Thursday;
                case DayOfWeek.Thursday:
                    Console.WriteLine("Watch a movie");
                    break;
                case DayOfWeek.Friday:
                    Console.WriteLine("Take out the trash");
                    goto case DayOfWeek.Tuesday;
                case DayOfWeek.Saturday:
                    Console.WriteLine("Relax");
                    break;
            }

This results in the following output:

  • Sunday: Go to church; Relax
  • Monday: Read Ulysses
  • Tuesday: Call Dad; Relax
  • Wednesday: Do laundry; Watch a movie
  • Thursday: Watch a movie
  • Friday: Take out the trash; Call Dad; Relax
  • Saturday: Relax

Think carefully before using goto in a switch statement.  There are often more clear ways to implement the same logic.

#176 – Switch Statement Doesn’t Fall Through from Case to Case

Unlike C++, in C# you can’t force execution of a switch statement to “fall through” from one case clause to another by leaving out the break statement.  Each case clause must end with a break, goto, throw or return statement.

The following code results in a compile-time error.

            switch (carType)    // carType is a string
            {
                case "Saturn":
                    Console.WriteLine("Domestic car");
                case "Yugo":
                    Console.WriteLine("Inexpensive car");
                    break;
            }

Technically, the requirement is that the end of the statement block in a case clause must not be reachable–implying that you must transfer control out of the block, typically with a break statement.  This requirement means that it would be valid syntax to include an infinite loop in a case clause, without a break statement.

#175 – The default Clause of a switch Statement

Normally, if the value of the expression in a switch statement doesn’t match any of the values listed in the case clauses, control falls through the switch statement and none of the clauses are executed.

Optionally, you can provide a default clause, which will get executed if none of the case clauses are satisfied.

            switch (surname)       // surname is a string
            {
                case "Aarhus":
                case "Enevoldsen":
                    Console.WriteLine("Norwegian");
                    break;
                case "Brosnan":
                case "McGill":
                    Console.WriteLine("Irish");
                    break;
                case "Afonso":
                case "Silva":
                    Console.WriteLine("Portuguese");
                    break;
                default:
                    Console.WriteLine("UNKNOWN origin");
                    break;
            }

#174 – Multiple Case Statements in switch Statement Can Share Code

In a C# switch statement, you can group several case statements with the same block of code.  If the switch expression has a value matching any of the listed case statements, the corresponding code will be executed.

            switch (movieRating)    // 1-5
            {
                case 1:
                case 2:
                    Console.WriteLine("Not worth seeing");
                    break;
                case 3:
                case 4:
                    Console.WriteLine("Consider seeing it");
                    break;
                case 5:
                    Console.WriteLine("Absolutely must see it");
                    break;
            }

#173 – The switch Statement

Use the switch statement in C# to execute one of several different blocks of code based on the possible values of a single expression.

            // 1 = Easy, 2 = Normal, 3 = Hard
            uint gameDifficulty = GetDifficulty();

            uint score = GetScore();
            uint totalScore;

            switch (gameDifficulty)
            {
                case 1:
                    Console.WriteLine("This is an EASY game");
                    totalScore = score / 2;
                    break;
                case 2:
                    Console.WriteLine("This is a NORMAL game");
                    totalScore = score;
                    break;
                case 3:
                    Console.WriteLine("This is a HARD game");
                    totalScore = score * 2;
                    break;
            }

The type of the expression must be one of the built-in primitive value types, a string or an enum.

The expression is evaluated and if the resulting value is listed as a value in one of the case clauses, the statements within that case are executed.

Each case clause must be terminated with some sort of jump statement.  The break statement is typically used, which causes control to jump to the next statement following the switch statement.

#172 – Nested if Statements

The statement to be executed when an if statement’s boolean expression resolves to true can be another if statement.

            if (bob.IsSingle)
                if (TheGameIsOnToday())
                    WatchGame();
                else
                    PlayVideoGames();

Because the inner if/else is a single statement, it can follow the boolean expression of the outer if as the single statement to execute if the expression resolves to true.

This might lead to some confusion about which if statement the else applies to.  An else clause belongs to the last if that doesn’t have an else clause.

You could make this logic more clear by enclosing the inner if/else in braces.

            if (bob.IsSingle)
            {
                if (TheGameIsOnToday())
                    WatchGame();
                else
                    PlayVideoGames();
            }
            else
                DoWhateverWifeSays();

#171 – if/else Statement Can Have One or More Statements in Body

The if/else statement can be used to execute a single statement in both the if and the else part, or to execute a block of statements.  A block of statements can be executed if curly braces ({, }) are used.

            // Example 1 - block of statements
            if (age >= 50)
            {
                Console.WriteLine("Hey, you should consider joining AARP!");
                DisplayDetailsOfAARPMembership();
            }
            else
            {
                Console.WriteLine("You're still a young pup");
                DisplayInfoAboutVideoGames();
            }

            // Example 2 - single statements
            if (airfare < 850.00)
                BookTickets();
            else
                PlanARoadTrip();

            // Example 3 - mixed
            if (married)
            {
                KeepPlaceClean();
                RaiseKids();
                LearnInterpersonalSkills();
            }
            else
                PlayVideoGames();

#170 – The else Portion of an if Statement

An if statement can optionally include an else keyword and block of statements, which will execute if the boolean expression for the if statement evaluates to false.

            if (age >= 50)
            {
                Console.WriteLine("Hey, you should consider joining AARP!");
                DisplayDetailsOfAARPMembership();
            }
            else
            {
                Console.WriteLine("You're still a young pup");
                DisplayInfoAboutVideoGames();
            }

#169 – The if Statement Must Always Include a Boolean Expression

In C++, an if statement can use a conditional expression that resolves to a numeric value.  The statement following the if statement will execute when this expression resolves to any non-zero value.  This form of the if statement is not allowed in C#.

            uint leaves = CountLeavesInBackyard();

            // Works in C++, but is not allowed in C#
            if (leaves)
            {
                RakeLikeHeck();
            }

Since the if statement must use a boolean expression in C#, we’d rewrite the code as:

            if (leaves > 0)
            {
                RakeLikeHeck();
            }