Skip to content

Different type convertion behaviors in a method that returns an object using if and switch. #8565

Answered by HaloFour
johncao158 asked this question in Q&A
Discussion options

You must be logged in to vote

The switch expression can only have a single return type, which the compiler infers as double as that is the only compatible type between int, float and double. That is done separately from boxing to an object. If you want the switch expression to return a type of object, you can make the following change:

    type switch
            {
                1 => (object)a,
                2 => (double)a,
                3 => (float)a,
                _ => throw new ArgumentException()
            };

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by CyrusNajmabadi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants