Switch Expressions
Im trying to convert different numbers in a switch expression while switching over a Type and noticed a strange behavior, that when I do an int.Parse(...) Im actually getting a double out of the function, see my example here: https://dotnetfiddle.net/QrgZqP why is this designed this way?
C# Online Compiler | .NET Fiddle
Test your C# code online with .NET Fiddle code editor.
7 Replies
the switch expression tries to return the most specific common type of all the arms
the calculation of common type includes implicit conversion
because int converts to double, but double doesn’t convert to int, that’s the common type
and it’s not object because that’s less derived than double
i agree it seems bad here
but they're not switching on the type, they're doing a typeof == check
Im adding explicit (object) casts now, because this really got my mouth to drop for some minutes
yes, the problem is, one arm returns int, one arm returns double
so what should the switch expression return
it needs to cast both values to something
oh
that
Could also pass in the type as a generic, unless you really need to be able to pass arbitrary types
-# granted if you didn't need that I assume you would be using
INumber.Parse
Im more or less hand parsing json and just got the types of each property, so generics would be more of an hassle I think
Thanks for explanation @reflectronic