In: Computer Science
As it relates to C#:
Though the function of switch case and else if ladder is same, there are a number of difference between switch case and else if ladder, Explain the differences in two areas such (memory consumption, speed of processing, variable requirement) etc.
Answer:
We must select else if ladder when
We must select switch case when
Differences between else if ladder and switch case in above mentioned two areas as follows:
1. Speed of processing: Switch statement's speed of processing is faster than the if-else-if ladder due to the compiler's ability to optimise the switch statement. While in if-else-if ladder, the code must process each if statement in the order determined by the programmer. Switch statement is good if provided number of cases are good. If there are few cases then there will be no difference in speed. Hence prefer switch if the number of cases are more than 5 otherwise, you may use if-else too.
2. Variable requirements: Variables required for the else if statement evaluation are integer, character, pointer or floating-point type or boolean type, while switch statement evaluates only character or a integer datatype variable.
Please give thumbsup, if you like it. Thanks.