@333fred asked me
Given the following code, we cannot determine a best type for the switch expression and the code does not compile. Why can't we determine that the best type is
A
, given that's the target type of the expression?class A { } class B : A { } class C : A { } class D { void M() { A a = null; a = a switch { B b => b, C c => c, _ => throw new System.Exception(), }; } }Casting one branch to
A
fixes the code
My initial reaction was
We use the same inference algorithm for
new []{ b, c }
and() => { if (b) return b; else return c; }
andc ? b : c
andM(b, c)
whereT M<T>(T x, T y)
. The general philosophy is that we avoid inferring a type that wasn't one of the input types. What if they had a common interface but not a common base class? What if they had two common interfaces? We just don't do that. We use "target type" only for certain conversions. We don't have a "conversion from array creation" or "conversion from conditional expression" and similarly we won't have a "conversion from switch expression".
However, my answer was not satisfactory to either @333fred or myself.
This is a proposal to "do that".
ProposalCurrently, a switch expression is specified to have a type that is the inferred common type of the expressions in the switch arms. It is (currently) required that there be such a common type.
Instead, I propose
T
if there is an implicit conversion from every arm's value expression to T
.T
be the type of the switch expression, either the target type of the switch expression conversion, or if it was not subject to such a conversion the expression's natural type. It is an error if T
does not exist. It is an error if a switch arm's expression cannot be implicitly converted to T
.alrz, Logerfo, spydacarnage, Austin-bryan, morsiu and 13 more
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4