Florian Koch
Florian Koch

Reputation: 1502

Why is enum cast on short possible but not boxed generic enum cast?

I just encountered a weird restriction while porting explicitly typed code in a converter to generic code:

When having a short (Int16) it is possible to cast it to an enum type. When doing the same with a generic enum type and boxed cast ((T)(object)value) this is an invalid conversion.

I was able to make the conversion successful by adding a third cast. It now looks like this:

Int16 numericValue;
...
var enumValue = (TEnum)(Object)(Int32)numericValue;

Why is that? The following (old) code worked just fine:

Int16 numericValue;
...
var enumValue = (MyEnum)numericValue;    

Upvotes: 1

Views: 124

Answers (1)

Jotrius
Jotrius

Reputation: 657

This is a problem of boxing and unboxing. When you unboxing the object, you can only unbox to the type of the value that was originally boxed: https://msdn.microsoft.com/de-de/library/yz2be5wk.aspx

In your case, you box an Int16 to an object:

Int16 numericValue;
...
var boxedValue = (object)numericValue;

and then you try unbox it as an Int32 (enum is Int32) and this is not possible:

var enumValue = (TEnum)boxedValue; // -> System.InvalidCastException

Upvotes: 2

Related Questions