Interview answers verified by specialists.

Find interview questions and answers on this website:

See right interview answers on 30 common job interview questions

How Does the "switch-case" Statement Work?

The structure switch-case chooses which part of the programming code to execute based on the calculated value of a certain expression (most often of integer type). The format of the structure for choosing an option is as follows:
switch (integer_selector)
case integer_value_1:
case integer_value_2:
// …
The selector is an expression returning a resulting value that can be compared, like a number or string. The switch operator compares the result of the selector to every value listed in the case labels in the body of the switch structure. If a match is found in a case label, the corresponding structure is executed (simple or complex). If no match is found, the default statement is executed (when such exists). The value of the selector must be calculated before comparing it to the values inside the switch structure. The labels should not have repeating values, they must be unique.
As it can be seen from the definition above, every case ends with the operator break, which ends the body of the switch structure. The C# compiler requires the word break at the end of each case-section containing code. If no code is found after a case-statement, the break can be omittedand the execution passes to the next case-statement and continues until it finds a break operator. After the default structure break is obligatory.
It is not necessary for the default clause to be last, but it’s recommended to put it at the end, and not in the middle of the switch structure.