0

I was reading unboxing and came across this code:

object obj = 22;

long l = (long)obj;

when I ran this code, it throws an exception InvalidCastException

I do not understand why?

For example Microsoft documentation on Boxing and Unboxing shows similar example that works:

int i = 123;
// The following line boxes i.
object o = i;
o = 123;
i = (int)o;  // unboxing
Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • 1
    What makes you think the compiler would interpret the literal `22` as a `long` (and not an `int`)? – Mathias R. Jessen Feb 02 '22 at 18:03
  • 2
    That's because `22` is an int. Try `object obj = 22L;` instead. – juharr Feb 02 '22 at 18:03
  • I've added results of your research to the question (please do that yourself for future question). I'm afraid it made question a bit more confusing - so please [edit] to add your version of the research and your reasoning why your code should work. – Alexei Levenkov Feb 02 '22 at 18:13
  • Or do: `long l = Convert.ToInt64(obj);` – Luuk Feb 02 '22 at 18:17

0 Answers0