Switch Case in C#

(Last Updated On: February 5, 2019)

Learn switch case in C# language with simple explanation, doubts and code example.

Switch case statement in C# is also conditional statement. In switch condition e.g. switch(value), the value of variable is matched to case written in it body. Whatever case matches the value of variable, that block get executed and exit from the switch case block on break statement.

Syntax of Switch Case in C#



Notice the colon : symbol after case value e.g. case value-2 : to start the block of a case.


In a case block, you can write many statements e.g. using if else conditions, calling methods etc. Example below.

Code Example of Switch Case in C#

In below switch case code example, value of variable var is 2. So, control will go directly to case 2: and executes its block and exit the entire switch case block on break statement. So, output of the program will be “Case -2 block”.

If no value is matched with any case e.g. if value of variable var you set to 5. there is no case 5, so control will execute default block.



What if I remove break from case 1, as given below in code?

Answer: If we remove break from case 1 and if supply value of var to 1, then after compiling the code an error will raise stating that “Control cannot fall through from one case label (‘case 1:’) to another”.



What if I remove all breaks from switch case block?

If you remove all breaks, compiler will throw an error stating that Control cannot fall through from one case label (‘case 1:’) to another.



DOUBT: Is it necessary to use break statement after last case e.g. default, in switch case block?

for example,

Answer: must required a break statement for any case in switch. other wise control cannot flow from one control to another.
even if default case is first case or last case in switch it must required a break statement to avoid compilation error.

However, it is good to use break in default to maintain consistency. Meaning, use break, for all cases in switch. It avoids the compilation error.

Code example:
Writing case after default. So, good to use break in default.