Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# long data type unboxing issue

Tags:

c#

c#-4.0

We can cast int to long.
Why is the following piece of code gives a run time error.

object o = 9;
long i = (long)o;
Console.WriteLine(i);

I am new to C#.

like image 208
Indranil Avatar asked Mar 16 '26 08:03

Indranil


2 Answers

The existing answers rightly explain why you get an exception, but don't really show what you could do instead. First casting to int is the typical answer, but only works if you know that the original value was an int. If the original value could be either int or long, then unboxing as int could fail just as well.

The simple way to change your code to something that works is by not attempting to do it yourself. .NET Framework already has a method to do exactly what you want: Convert.ToInt64. So just write

long i = Convert.ToInt64(o);

and let the runtime worry about any internally required intermediate type conversions.

Per this bit of documentation:

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null or a reference to an incompatible value type will result in an InvalidCastException.

So, you have to unbox to int first and then convert to long (an implicit conversion exists):

object o = 9;
long i = (int)o;
like image 21
Charles Mager Avatar answered Mar 17 '26 21:03

Charles Mager



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!