Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not all code paths return a value - but they do

The following extract of code is failing to compile resulting in not code paths return a value. Both types Test1StandardChargeCalculator and Test2StandardChargeCalculator are derived from the return type.

I know how to fix this, but my question is why should I have to? A bool is a value type - hence can only represent true or false, both of which are catered for in this snippet. So why the failed compilation?

internal StandardChargeCalculator Create()
{
      bool value = true;

      switch (value)
      {
          case true:
              return new Test1StandardChargeCalculator();
          case false:
              return new Test2StandardChargeCalculator();
      }
} //not all code paths return a value
like image 416
m.edmondson Avatar asked Nov 30 '22 06:11

m.edmondson


2 Answers

When using a switch statement, the compiler does not understand that when you are using a boolean type to switch on there can only be two results.

The error occurs because you do not have a default case.

Don't use a switch for boolean test - use an if statement:

  bool value = true;

  if(value)
  {
      return new Test1StandardChargeCalculator();
  }

  return new Test2StandardChargeCalculator();
like image 157
Oded Avatar answered Dec 02 '22 18:12

Oded


Why do you think the compiler should special-case boolean and detect that all possible values have a case statement?

If you were writing a compiler, would you invest development effort and increase the risk of bugs by implementing this?

like image 38
Joe Avatar answered Dec 02 '22 19:12

Joe