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
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();
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With