Posted by : Sudhir Chekuri Thursday, 31 December 2015

The switch statement which allows you to compare an expression with a number of different values.

Syntax of C#.NET Switch statement


switch(variable)
{
case value1:
statements;
break;
case value2:
statements;
break;
-------------------
-------------------
-------------------
default:
statements;
break;

Example program using C#.NET switch statement
Program

using System;

namespace Switch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter number");
            int no = Convert.ToInt32(Console.ReadLine());
            switch (no)
            {
                case 1:
                    Console.WriteLine("One");
                    break;
                case 2:
                    Console.WriteLine("Two");
                    break;
                default:
                    Console.WriteLine("Invalid");
                    break;
            }
            Console.ReadKey();
        }
    }
}

Output

Enter number
1
One

Output

Enter number
2
Two

Output

Enter number
12
Invalid

Explanation

In the above example we can give input is 1 it prints output as One, input is 2 print output as Two, if we can give input is any number except 1 and 2 the output prints Invalid because if we can give input is 1 compiler executes case1 and we give i/p is 2 executes case2 then print output as One and Two. We give any other number except 1 and 2 default case will execute and prints Invalid.

Example program for C#.NET switch statement
Program

using System;

namespace Switch2
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 4;
            switch (i)
            {
                case 1:
                case 2:
                case 3:
                    Console.WriteLine("One");
                    break;
                case 4:
                case 5:
                    Console.WriteLine("Two");
                    goto case 1;
                default:
                    Console.WriteLine("Invalid");
                    break;
            }
            Console.ReadKey();
        }
    }
}


Output

Two
One

Explanation

In the above example we can assign i value as 4. So directly case 4 is executed and print output is Two, next no break statement is available. instead of break we write goto statement as goto case1,then after the execution go and starts from case1 then the output one will be printed. Finally the output will be Two and One printed line by line.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

Blog Archive

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -