Why does C# pattern matching return float for this?

65 Views Asked by At

Here is the source code

bool v = false;

object x = v switch {
 true => 0.0f,
 false => 100L,
};

the pattern match returns different numeric types for the 2 branches, and the values is converted to obejct as base class

I expect it x to be float for true branch, and int for false branch, but the result is, the return value is derived to float

And if the value is boxed in branches, it worked

object x = v switch {
 true => 0.0f as object,
 false => 100L as object,
};

I can understand the pattern matching as a whole to derive this result, but I consider it a bug, any explanation to help me?

1

There are 1 best solutions below

0
Salman A On

The switch expression returns exactly one type. It says here that:

The type of the switch_expression is the best common type (§11.6.3.15) of the expressions appearing to the right of the => tokens of the switch_expression_arms if such a type exists and the expression in every arm of the switch expression can be implicitly converted to that type.

The "best common type" mechanism is the same one used for (e.g.) initializing implicitly typed arrays:

implicitly typed arrays with mixed types