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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers