Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert long to object then to ulong

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
like image 815
ricky Avatar asked Sep 17 '12 12:09

ricky


2 Answers

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

like image 92
Rune FS Avatar answered Oct 16 '22 18:10

Rune FS


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.

like image 6
Falanwe Avatar answered Oct 16 '22 19:10

Falanwe