why C# can't implicitly convert a long var to an object var then to ulong?
long a = 0;
Object c = a;
ulong b = (ulong)c; // throw exception here
you can only unbox to the exact same type as was boxed
Object c = a
boxes a which is a long
ulong b = (ulong)c;
tries to unbox c as a ulong but it is a long and hence fails.
ulong b = (ulong)((long)c);
would work since it unboxes c as a long. c being long this will work and you can cast long to ulong
If you box a value type T, you can only unbox it as itself or as a Nullable ( T? ). Any other cast is invalid.
That's because a cast from object can never be interpreted as a conversion, whereas the is a conversion between long and ulong.
So this is legal:
var c = (long) b;
This is also legal:
var c = (long?) b;
But this is not:
var c = (ulong) b;
To do what you want to, you have to cast twice: the first is only unboxing, and the second is the actual conversion:
var c = (ulong)(long) b;
For further information, see this blog post by Eric Lippert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With