This tutorial is about switch statement in C#. Switch statement is used when you have to evaluate a variable for multiple values
Don’t forget to check out our site for more free how-to videos!
– our feed
– join us on facebook
– our group in Google+
We have seen the if—else construct. Another conditional statement is the switch statement in C#. It is used when you have to evaluate a variable for multiple values.
In C, switch statements are defined by the following syntax:
When the switch statement in C# is executed, the variable in the switch statement is evaluated. The value of the variable is compared with each case constant. If one of the case constants is equal to the value of the variable given in the switch statement, control is passed to the statement following the match case statement. A break statement is used to exit the switch—case construct. If none of the cases match, the default block gets executed.
The keyword switch is followed by the variable in parentheses. Each case keyword is followed by a possible value for the variable.
The points to be noted here are:
• The data type of the constants should match the data type of the variable being evaluated by the switch construct.
• Before entering the switch construct, a value should be assigned to the switch variable.
• break statement completes a case construct and its compulsory to finish the case.
Step 1: Implementing Switch Statement
A complex if—else construct can be replaced by a simple switch—case construct.
The following code is an example of nested if—else construct:
else if (grade==2)
This code can be replaced by a switch—case construct as follows:
In C, switch statement construct evaluates an expression only once at the top, where as the if—else construct evaluates the expression for each if statement. Thus it can be said that the switch statement in C# is a simpler form of the nested if—else construct.
Xem Thêm Bài Viết Khác:https://wijstaanvooronzegrondrechten.org/cong-nghe