Wednesday, August 14, 2013

C# - The Switch case

The Switch statement provides us the ability to run a specific code parts based on a list of sections that are defined via a specific variable.

Example 1 – Using If/Else:
class Program
    {
        static void Main(string[] args)
        {           
                Console.WriteLine("Enter a number Between 0 - 4 : ");
                int usernumber = int.Parse(Console.ReadLine());
                if (usernumber == 0)
                {
                    Console.WriteLine("Min                     Number");                  
                }
                else if (usernumber == 4)
                {
                    Console.WriteLine("Max Number");
                }
                else if (usernumber > 0 || usernumber < 4)
                {
                    Console.WriteLine("Number in range");
                }           
        }
    }

Example 2 – Same code with ‘Switch’ case implementation:
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number Between 0 - 4 : ");
            int usernumber = int.Parse(Console.ReadLine());
            switch (usernumber)
            {
                case 0:
                    Console.WriteLine("Min Number");
                    break;

                case 1:
                    Console.WriteLine("Number in range");

                    break;
                
                case 2:
                    Console.WriteLine("Max Number");

                    break;
                  
                default :
                    Console.WriteLine("number is out of range");
                    break;
            }
        }
    }

As you can see,
The same code can be written in two logical ways, but the switch provide a better logical structure. 
The structure of the  Switch statement 

Switch (User Number):
All cases executed based on the ‘User Number’ value, the application passes each case and test the variable number.

Case:
Every case covers different part of code that can be executed based on the variable value.

Default:
This section is NOT mandatory .if we decide to use it the code will executed only in case that all other cases failed to be executed based on variable value.

Break:
I will explain it in future article, but for now all we need to know is that we must use it to exit the case section after code completed.

No comments:

Post a Comment

My Presentations