Search code examples
c#.netcompiler-errorsvalue-type

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

Solution

  • 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();