DataReader: Specified cast is not valid (Int32)

moldovanu picture moldovanu · Apr 12, 2012 · Viewed 22.8k times · Source

Why does SqlDataReader throw an exception when converting 0 to integer?

?dataReader(3)
0 {Short}
    Short: 0
?dataReader.GetInt16(3)
0
?dataReader.GetInt32(3)
{"Specified cast is not valid."}
    _HResult: -2147467262
    _message: "Specified cast is not valid."
    Data: {System.Collections.ListDictionaryInternal}
    HelpLink: Nothing
    HResult: -2147467262
    InnerException: Nothing
    IsTransient: False
    Message: "Specified cast is not valid."
    Source: "System.Data"
    StackTrace: "   at System.Data.SqlClient.SqlBuffer.get_Int32()     
                    at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)"
    TargetSite: {Int32 get_Int32()}

Answer

Marc Gravell picture Marc Gravell · Apr 12, 2012

It isn't a convert - it is a cast. The same as:

short x = 0;
object y = x;
int z = (int)y; // BOOM! InvalidCastException Specified cast is not valid.

In both cases, a short is not an int.

If unsure of the type, you might try:

int i = Convert.ToInt32(dataReader.GetValue(3));