#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #173 – The switch Statement

  1. David says:

    In C, you can leave out the “break” to fall through to the next case. C enthusiasts say that this gives you incredible flexibility to do weird edge cases, but far more often it’s just a source of bugs when you forget the “break.” C# does this better.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: