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
-
internal class Program
{
static void Main(string[] args)
{
var a = (int)ToValue(1, 1); // OK
var b = (double)ToValue(1, 2); // OK
var c = (float)ToValue(1, 3); // OK
var a2 = (int)ToValue2(1, 1); // FAIL, Unable to cast object of type 'System.Double' to type 'System.Int32'
var b2 = (double)ToValue2(1, 2); // OK
var c2 = (float)ToValue2(1, 3); // FAIL, Unable to cast object of type 'System.Double' to type 'System.Single'
}
static object ToValue(int a, int type)
{
if (type == 1)
{
return a;
}
if (type == 2)
{
return (double)a;
}
if (type == 3)
{
return (float)a;
}
throw new ArgumentException();
}
static object ToValue2(int a, int type)
=> type switch
{
1 => a,
2 => (double)a,
3 => (float)a,
_ => throw new ArgumentException()
};
} The second method "ToValue2" will always return a "Double" value. |
Beta Was this translation helpful? Give feedback.
Answered by
HaloFour
Nov 8, 2024
Replies: 1 comment
-
The switch expression can only have a single return type, which the compiler infers as type switch
{
1 => (object)a,
2 => (double)a,
3 => (float)a,
_ => throw new ArgumentException()
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
CyrusNajmabadi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The switch expression can only have a single return type, which the compiler infers as
double
as that is the only compatible type betweenint
,float
anddouble
. That is done separately from boxing to anobject
. If you want theswitch
expression to return a type ofobject
, you can make the following change: