C# Switch Case Statement

As we know that we use If-Else statement when we have to perform any conditional bases operation. When the condition become true we execute the If block statements and when the condition is false we execute Else block. But sometimes there are a group of conditions where we have to perform one from the group. In this case we use Switch-Case statements. A Switch statement execute the case condition corresponding to the value of expression. First we will use the syntax of using Switch-Case Example. and Then we will use an example.




Syntax:

switch(Expression)
{
   Case Expression1: // Write statements
                          Break;
   Case Expression2: // Write statements
                          Break;
   Case Default: // Write statements
                         Break;
}
Example:
private void btnDays_Click(object sender, EventArgs e)
        {
            int val = 5;
            switch (val)
            {
                case 1:
                    MessageBox.Show("Sunday");
                    break;
                case 2:
                    MessageBox.Show("Monday");
                    break;
                case 3:
                    MessageBox.Show("Tuesday");
                    break;
                case 4:
                    MessageBox.Show("wednesday");
                    break;
                case 5:
                    MessageBox.Show("Thursday");
                    break;
                case 6:
                    MessageBox.Show("Friday");
                    break;
                case 7:
                    MessageBox.Show("Saturday");
                    break;
                default:
                    MessageBox.Show("Out of range !!");
                    break;
            }
        }
admin (157 Posts)


Leave a reply

Your email address will not be published.

Comment moderation is enabled. Your comment may take some time to appear.