C#: The switch statement

This entry is part 49 of 71 in the series C#

An alternative to if else statement, the switch statement allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.

The expression used in the switch statement must return an int, a String, or an enumerated value.

switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below).

Its syntax is:
switch (expression)
    case value_1 :
        [break | goto label;]
    case value_2 :
        [break | goto label;]

For the example below , a string case of “1” and a string case of “small” are similar.

Switch Statement
using System;

namespace Conditional
    static class Program
        static void Main()
            Console.WriteLine("Please choose the size of your T-shirt:");
            Console.WriteLine("1=small 2=medium 3=large");
            Console.Write("Please enter your selection: ");
            string str = Console.ReadLine();
            switch (str)
                case "1":
                case "small":
                    Console.WriteLine("You have choosen size small");
                case "2":
                case "medium":
                    Console.WriteLine("You have choosen size medium");
                case "3":
                case "large":
                    Console.WriteLine("You have choosen size large");
                    Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
            Console.WriteLine("Thank you for your business.");

Execution of the statement list in the selected switch section begins with the first statement and proceeds through the statement list, typically until a jump statement, such as a break, goto case, return, or throw, is reached.

At that point, control is transferred outside the switch statement or to another case label.

If there is no default section, the prompt about the invalid selection will not be executed.  No action is taken and control is transferred outside the switch statement.

So in a way, you have to ensure the user have entered the selection correctly.


Series Navigation<< C#: The continue statement
C#: Inheritance or specialization >>
Posted in

Leave a comment

Leave a Reply