You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Check that switch expressions with a natural type do not cause additional conversions #1739
Okay, moving the first of Kalle's examples here, and adding a Main method:
classB{}classC1:B{}classC2:B{}structS{publicstaticimplicitoperatorS(B_){Console.WriteLine("S(B)");returndefault;}publicstaticimplicitoperatorS(C1_){Console.WriteLine("S(C1)");returndefault;}publicstaticimplicitoperatorS(C2_){Console.WriteLine("S(C2)");returndefault;}}classP{publicstaticSM1(inti){// First converts from C1, C2, or B to the switch common type B, then from B to S.returniswitch{1=>newC1(),2=>newC2(), _ =>newB()};}publicstaticSM2(inti){// Converts C1 or C2 directly to S.returniswitch{1=>newC1(),2=>newC2(), _ =>thrownewSystem.ArgumentException()};}}classProgram{staticvoidMain(){P.M1(1);P.M1(2);P.M1(3);P.M2(1);P.M2(2);}}
Observed behavior (admittedly with .NET 10) is:
S(B)
S(B)S(B)S(C1)S(C2)
In other words, the "natural type" of the switch expression is used in the case of M1 before switch expression conversions.
I don't think this is currently covered in the spec.
We may be able to fix it by adding "which does not have a type " to 10.2.18:
Before:
There is an implicit conversion from a switch_expression (§12.11) to every type T for which there exists an implicit conversion from each switch_expression_arm’s switch_expression_arm_expression’s to T.
After:
There is an implicit conversion from a switch_expression (§12.11) which does not have a type to every type T for which there exists an implicit conversion from each switch_expression_arm’s switch_expression_arm_expression’s to T.
Added "meeting: discuss" so we can check if that makes sense; it'll be easy to whip up a PR if so.
Activity
jskeet commentedon Jul 22, 2026
(Shouldn't be too hard to check and/or fix, so marked as C# 8 - but if it becomes more fiddly, we may make it "pre-C# 9")
jskeet commentedon Aug 26, 2026
Okay, moving the first of Kalle's examples here, and adding a Main method:
Observed behavior (admittedly with .NET 10) is:
In other words, the "natural type" of the switch expression is used in the case of M1 before switch expression conversions.
I don't think this is currently covered in the spec.
We may be able to fix it by adding "which does not have a type " to 10.2.18:
Before:
After:
Added "meeting: discuss" so we can check if that makes sense; it'll be easy to whip up a PR if so.
KalleOlaviNiemitalo commentedon Aug 26, 2026
Perhaps clearer with a comma in "does not have a type, to every type".
jskeet commentedon Sep 9, 2026
Meeting resolution: proposal is fine. @jskeet to create a PR.
Restrict switch_expression conversions
Restrict switch_expression conversions (dotnet#1806)