I've looked around for some time now and can't seem to find a direct answer to my question.
I am creating (as an exercise, self induced, not homework) a basic Cast<T>
method, where an object
is supplied and if the conversion is valid then T
is returned. The initial method was incredibly straight forward. Simply perform implicit conversion and return the result.
internal T Cast<T>(object val) => (T)val;
My thinking here was that this would either work or it would throw an exception at runtime. Well, it does throw an exception at runtime, which I expect to happen due to attempting to cast string
to int
for example.
However, what I didn't expect, is for it to fail to cast int
to double
or vice-versa. I can do this when explicitly stating types:
int a = 0;
double b = 0;
a = (int)b;
b = (double)a;
All of that works fine and throws no exceptions and from my understanding this is by design for the same reason that char
to string
works. The types are similar in which only their ranges are different. Per MSDN:
int
- -2,147,483,648 to 2,147,483,647
double
- ±5.0 × 10^−324 to ±1.7 × 10^308
Thus casting from double
to int
caps the value to int.MaxValue
or MinValue
respectively. For example, the following code will print int.MinValue
both times:
int a = int.MaxValue;
double b = double.MaxValue;
a = (int)b;
Console.WriteLine($"int: {a}");
b = (double)a;
Console.WriteLine($"double: {b});
This makes me curious, is there a reason why we can't cast from object
to T
when our object
is of type int
and our T
is of type double
or is this just a .NET shortfall?