Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataReader GetInt32() & GetInt16()

Tags:

c#

.net

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;
like image 698
KBBWrite Avatar asked Oct 20 '11 18:10

KBBWrite


1 Answers

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() read int, long and maybe even decimal without complaining?
I think better not.

like image 114
Henk Holterman Avatar answered Oct 19 '22 00:10

Henk Holterman