When you unbox, it has to be to one of the following:
- The exact same type
- The nullable form of the exact same type
- If it's an enum type value, then you can unbox to the underlying type
- If it's an integral type value, you can unbox to an enum which uses that underlying type
Examples:
using System;
class Test
{
enum Foo : short
{
Bar = 1
}
static void Main()
{
short x = 1;
object o = x;
short a = (short) o;
short? b = (short?) o;
Foo c = (Foo) o;
o = Foo.Bar;
short d = (short) o;
}
}
Anything else will give an exception. In particular, you can't unbox to a different type even if there's an implicit conversion from the actual type to your target type, which is what you're trying to do on the last line of your example.
You also can't unbox from an integral value to a nullable form of an enum with the same underlying type (or the reverse situation).
Note that if you box a nullable value type value, the result is either null (if the original value was the null value for the type) or the boxed non-nullable value... there's no such thing as a "boxed nullable value type" if you see what I mean.