1

I'm tryng to convert a numeric type on my mysql database (smallint(6)) and I'm getting the following error:

Unable to cast object of type 'System.Int16' to type 'MyEnum'.

My Enum is:

public enum MyEnum
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3,
    Value4 = 4
}

The conversion is happening here:

MyEnum enumHere = (MyEnum)reader["cod_sist_orig"];

Reader is a IDataReader and the column is a not nullable column and the value comming from the database is 1.

Felipe Deveza
  • 1,899
  • 3
  • 19
  • 32

1 Answers1

1

You need cast to short first:

MyEnum enumHere = (MyEnum)(short)reader["cod_sist_orig"];

Or change the enum's underlying type to short:

public enum MyEnum : short
{
    Value1 = 1,
    Value2 = 2,
    Value3 = 3,
    Value4 = 4
}

For more info check out the docs for unboxing and relevant part of the language specification.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132