Why are SWITCH and IF different in terms of Variable assignement

c#, switch-statement

Solution

You are missing the `default` case in your switch statement. The same would happen if you had written:

if (decision)
{
   toBeAssigned = getValuesA();
}
else if (!decision)
{
   toBeAssigned = getValuesB();
}

This happens, because the compiler doesn't know how much cases there are and always assumes that you have not covered them all, unless you have a `default` statement, which basically sais "if all other cases are not met, do this". The same goes for `if` and `else`: `if(...)` and `else if(...)` are your "case: " and `else` is your "default: "

Problem

I am currently using IF-Statements most of the time, but I am increasingly fond of the switch case statement, because sometimes it is a lot more readable. But I am wondering why the Compiler does not understand switch as well as an `if`. An example: ``` bool decision = false; IEnumerable<string> toBeAssigned; if (decision) { toBeAssigned = getValuesA(); } else { toBeAssigned = getValuesB(); } foreach (var elem in toBeAssigned ) { // do something } ``` This should compile fine and toBeAssigned can be used in the foreach without a problem. BUT: ``` bool decision = false; IEnumerable<string> toBeAssigned; switch(decision) { case true: toBeAssigned = getValuesA(); break; case false: toBeAssigned = getValuesB(); break; } foreach (var elem in toBeAssigned ) { // do something } ``` Does not compile for me - the compiler complains that the Value for toBeAssigned is never assigned. Since both should compile to the same IL, I am curious why the Compiler treats both cases differently.

Original source