How do I use switch statement?

Category: Introduction, viewed: 139 time(s).

The example below demonstrate a simple use of the switch statement. A switch statement can be a good replacement for a long if-else-if-else selection statement.

A switch statement handles multiple selection by passing control to one of its case statement within its body. Selection will be handled by the case statement that matches the value of the switch. switch statements can have many case but each case should have a unique value.

Each of case block should be closed by the break statement. This include the last statement whether it is a case or a default block.

If no case condition matched the switch value the control will be transferred to default block. If the default is not available the control will be transferred out side the switch.

using System;

namespace Kodecsharp.Example.Intro
{
    class SwitchDemo
    {
        [STAThread]
        public static void Main(string[] args)
        {
            // Prompt user a message to enter a week day.
            Console.Write("Please enter week day: ");
            // Read user input value and convert it into integer value
            int day = Int32.Parse(Console.ReadLine());

            // Declare a variable to hole the dayName value.
            string dayName = "";

            //
            // Use the switch statement to check which week day value is
            // entered by the user.
            //
            switch (day)
            {
                case 1:
                    dayName = "Sunday";
                    break;
                case 2:
                    dayName = "Monday";
                    break;
                case 3:
                    dayName = "Tuesday";
                    break;
                case 4:
                    dayName = "Wednesday";
                    break;
                case 5:
                    dayName = "Thursday";
                    break;
                case 6:
                    dayName = "Friday";
                    break;
                case 7:
                    dayName = "Saturday";
                    break;
                default:
                    dayName = "Wrong input. Should be between 1 - 7";
                    break;
            }

            // Print out the selected week day.
            Console.WriteLine("Day name: " + dayName);
            Console.ReadLine();
        }
    }
}

Here is an example result of the program:

Please enter week day: 4
Day name: Wednesday
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page