Reza ArabQaeni
Reza ArabQaeni

Reputation: 4908

Why dynamic casting throw exception?

I have a enum:

enum MyEnum
{
    First,
    Second
}

I could cast int to Enum:

var sample1 = (MyEnum)1;

But i got exception on dynamic convertion with this:

var sample2 = System.Convert.ChangeType(1, typeof(MyEnum));
//Invalid cast from 'System.Int32' to 'ConsoleApplication1.Program+MyEnum'.

Why dynamic casting throw exception?

I'm not looking for a solution and just like to know why the exception is thrown?

Thanks

Upvotes: 2

Views: 362

Answers (1)

RB.
RB.

Reputation: 37222

Short answer: Convert.ChangeType can only convert built-in types to a pre-defined set of classes. In the case of Int32, this is the same set of explicit classes as allowed by IConvertible.

Long answer: Under the hood, the Convert.ChangeType method will call Int32.IConvertible.ToType.

This will in turn call the internal method Convert.DefaultToType which will work through a pre-defined list of types and call the appropriate method from IConvertible (e.g. if you requested a DateTime, it will call ToDateTime). However, there is an interesting one in there from your point of view:

if (targetType == Convert.EnumType)
{
    return (Enum)value;
}

Which you might think would allow your code to work. However, it won't - the type of your enum is not System.Enum - it is a subclass of that.

Upvotes: 4

Related Questions