ideas | discover | explore

Wednesday, September 21, 2011

C# 7 - Switch statement

1. Create a new console project.
2. Edit the Program.cs file as shown below.

 static void Main(string[] args)
        {
            Console.WriteLine("What is your most favorite sweet stuff?");
            Console.WriteLine("[1]Chocolate");
            Console.WriteLine("[2]Candy");
            Console.WriteLine("[3]Lollipop");
            Console.WriteLine("[4]Sugar");
            Console.WriteLine("[5]Honey");
            Console.WriteLine("[6]Cake");
            Console.Write("Enter your choice: ");
            string choice = Console.ReadLine();
 
            switch (choice)
            {
                case "1":
                    Console.WriteLine("Chocolate, chocolate, chocolate!");
                    break;
                case "2":
                    Console.WriteLine("Candy, candy, candy!");
                    break;
                case "3":
                    Console.WriteLine("Lollipop, lollipop, lollipop!");
                    break;
                case "4":
                    Console.WriteLine("Sugar, sugar, sugar!");
                    break;
                case "5":
                    Console.WriteLine("Honey, honey, honey!");
                    break;
                case "6":
                    Console.WriteLine("Cake, cake, cake!");
                    break;
                default:
                    Console.WriteLine("Hmmm, I don't know what you're favorite is.");
                    break;
            }
            
            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
 
        }
3. Press F5 to run and see the results.

4. Thank you.

The switch statement is used to add condition to a piece of code. Its syntax is:

switch(<expression>)
                case <expression result>:
                                //code to execute
                                break;
                case <expression result>:
                                //code to execute
                                Break;
                .
                .
                .
                default:
                                //code to execute if there are no matching case
                                break;


expression – could be anything that would result in a value that would get evaluated in each of the cases.

No comments: