C
C#5d ago
gönnyd

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
reflectronic
reflectronic5d ago
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
jcotton42
jcotton425d ago
but they're not switching on the type, they're doing a typeof == check
gönnyd
gönnydOP5d ago
Im adding explicit (object) casts now, because this really got my mouth to drop for some minutes
reflectronic
reflectronic5d ago
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
jcotton42
jcotton425d ago
oh that
Thinker
Thinker5d ago
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
gönnyd
gönnydOP5d ago
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

Did you find this page helpful?