I am trying to read a smallint column value using SqlDataReader.
The dataReader.GetInt32() is throwing exception as “The specified cast is not valid.”
But
dataReader.GetInt16()
is working fine too.
Can you someone explain why the GetInt32() fails provided Int16 can be assigned to Int32 as here
Int16 i16 = 1;
Int32 i32 = i16;
The
GetInt##()methods look for an exact match, the ‘invalid cast’ error is about the DbType to ClrType conversion.You are correct that GetInt32() could have been made to read smaller types but then that could happen inadvertently as well.
Should
GetDouble()readint,longand maybe evendecimalwithout complaining?I think better not.