Christian Sauer
Christian Sauer

Reputation: 10889

Why are SWITCH and IF different in terms of Variable assignement

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.

Upvotes: 3

Views: 146

Answers (2)

Mario Stoilov
Mario Stoilov

Reputation: 3447

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: "

Upvotes: 8

Bathsheba
Bathsheba

Reputation: 234635

Your if statement covers all possible cases but the compiler does not realise that the switch does that too: you're missing a default case.

The compiler thinks that there is a possibility that toBeAssigned might not be set to anything, so it emits the error.

Upvotes: 11

Related Questions