2.5: Switch Statements

In this module we'll study a type of conditional called a Switch.

File Location

  1. Right click on the solution you made in the first module

  2. Go to Add > New Project and select Console App (.NET Framework)

  3. Name it 0.02_Switches

  4. Write your code for this module within Program.cs of that project

Switch Case

Let's start with an example of a switch case:

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What's your name?"); //1
            string inputName = Console.ReadLine().ToLower(); //2
            //3
            switch (inputName)
            {
                case "fred":
                    Console.WriteLine("Hey Fred, let's go golfing.");
                    break;
                case "karl":
                    Console.WriteLine("Let's hang.");
                    break;
                case "john":
                    Console.WriteLine("Sorry, I'm busy right now.");
                    break;
                default:
                    Console.WriteLine("Hey " + inputName + ", can I call you back in a minute?");
                    break;
            }
        }
    }

Discussion

  1. In the example above, we ask the user their name

  2. We store that name as inputName. To standardize the input, we use .ToLower()to convert the user's input to lowercase.

  3. We then use a switch case to go through the different values of inputName and have the console print the different outcomes. First, the program looks for fred, then karl, then john, and then has a case for none of those options, the default case.

  4. If 'fred' is the name entered, the program will run the expression in that case, and then it will stop.

Practice Challenge

Try making a switch case describing outputs for your different friends.

Practice Answer

Your switch would look something like this:

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What's your friend's name?");
            string friend = Console.ReadLine().ToLower();

            switch (friend)
            {       
                case "jay":
                    Console.WriteLine("Scool.");
                    break;
                case "paul":
                    Console.WriteLine("Paul is pretty cool.");
                    break;
                case "kenn":
                    Console.WriteLine("Kenn is pretty cool.");
                    break;
                case "carr":
                    Console.WriteLine("Coolest dude ever");
                    break;
                default:
                    Console.WriteLine($"I don't know {friend}.");
                    break;
            }
        }
    }

Feel free to do some more practice with switches, if you need it.

Next: Ternary Expressions

Last updated