A Boolean expression is used to execute the function in the if statement and can often
used to check multiple conditions at a time. The int expression is used in switch
statement to check each cause to see if it satisfies the conditions, then statement would
execute the code.
Definition of if-else
The if-else statements belong to selection statements in OOP. The general form of the if-else statements like as given below.
where “if” and “else” are the keywords, and the statements can be a single statement or a block of statements. The expression evaluates to be “true” for any non-zero value and for zero it evaluates to be “false”.
Definition of switch
The switch statements is a multiple-choice selection statement. The general form of the switch statement like as given below.
Further more differences of if and switch statement are as follows:
- Switch statement is convenient for expression of lengthy conditions as compared to If statement which gets more complex as number of conditions grow and the nested If also comes for playing.
- Switch statement allows easy proofreading while testing as well as removing bugs from source code while If statement makes editing inconvenient.
- Expression is evaluated and Switch statement is run according to the result of the expression that can be integer or logical while If statement is run only if result of the expression is True.
- Switch allows expression to have integer based evaluation while If statement allows evaluation on both integer and character based .
- Switch statement can be executed with all cases if the “break” statement is not used whereas If statement has to be true to be executed further.
Advantage of switch case in C#
Improving clarity is main reason for using switch. It is due to by reducing otherwise repetitive coding and also offering potential for faster execution through easy compiler optimization in most of the cases.
Drawbacks of switch over if statement
float constant cannot be used in the switch as well as in case, cannot use variable expression. We cannot use the same constant in two different cases and also relational expression in case.