invalid cast... object to personal type

  • Thread starter Thread starter franky
  • Start date Start date
F

franky

HI
I declare a enum like that:

public enum MyType
{
open = 1,
close= 2
};

I got a error when a try to do :
MyType var1;
int var2;
var1 = (MyType) cmd.ExecuteScalar();

//== but ok like this ===========
var2 = Convert.toInt32( cmd.ExecuteScalar() );
var1 = (MyType) var2;

Do I forgot something?
 
franky said:
I declare a enum like that:

public enum MyType
{
open = 1,
close= 2
};

I got a error when a try to do :
MyType var1;
int var2;
var1 = (MyType) cmd.ExecuteScalar();

//== but ok like this ===========
var2 = Convert.toInt32( cmd.ExecuteScalar() );
var1 = (MyType) var2;

Do I forgot something?

cmd.ExecuteScalar() returns an object. If it's returning an int, you
need to unbox it to int, and *then* cast to MyType. For instance:

MyType var1 = (MyType) (int) cmd.ExecuteScalar();
 
To further reinforce the point:
The boxing of the values results in the following IMO ridiculous scenario:

cmd.CommandText = "select top 1 tinyVal from myTable"; // Assume that
tinyVal field is TINYINT - an equivalent of byte

//This fails:
int ret = cmd.ExecuteScalar();

// But this works:
int ret = (byte)cmd.ExecuteScalar();
 
Back
Top