2

This code is compiled.

using System.IO;
using System;

class Program
{
    static void Main()
    {
        object obj = 0; 
        long x = (long) obj; 
        Console.WriteLine(x);
    }
}

In run-time it throws this Unhandled Exception:

System.InvalidCastException: Cannot cast from source type to destination type.
at Program.Main () [0x00000] in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type.
at Program.Main () [0x00000] in :0

The following chunk is compiled and run correctly.

static void Main()
    {
        object obj = 0; 
        long x = (int) obj; 
        Console.WriteLine(x);
    }

> 0

What's going on?

overcomer
  • 2,244
  • 3
  • 26
  • 39
  • Because the integer literal `0` is an `int`. You can only unbox a boxed value type to its original type. See [duplicate](http://stackoverflow.com/questions/1085097/why-cant-i-unbox-an-int-as-a-decimal) and [C# - Issues with boxing / unboxing / typecasting ints. I don't understand](http://stackoverflow.com/questions/8771476/c-sharp-issues-with-boxing-unboxing-typecasting-ints-i-dont-understand). – CodeCaster Sep 29 '15 at 10:44
  • try with `object obj = 0L;` – Robert Sep 29 '15 at 10:45
  • @CodeCaster so the exception is thrown during the unboxing operation? – overcomer Sep 29 '15 at 10:46
  • 1
    I was hoping you would know, because you have the code and can attach a debugger. :) But yeah, it is thrown during unboxing. – CodeCaster Sep 29 '15 at 10:47

0 Answers0