ricky
ricky

Reputation: 2108

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

Upvotes: 5

Views: 5769

Answers (4)

TaSwavo
TaSwavo

Reputation: 11

All the above result in a loss of data if the value is greater than the maximum value of a long (9,223,372,036,854,775,807).

ulong has a minimum of zero and a maximum of 18,446,744,073,709,551,615.

To convert without this risk use

ulong b = Convert.ToUInt64(c);

Upvotes: 1

Falanwe
Falanwe

Reputation: 4744

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.

Upvotes: 6

Freeman
Freeman

Reputation: 5801

Short and simple answer: beacuse long and ulong are not the same type. One is a signed long the other is an unsigned long.

Upvotes: 0

Rune FS
Rune FS

Reputation: 21742

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

Upvotes: 7

Related Questions