简体   繁体   中英

Getting value from an int column causes “no implicit conversion between 'int' and null” error

So I'm trying to retrieve a value from an INT , not an INT NOT NULL , column by means of

AnswerVal = !dataReader.IsDBNull(5) ? dataReader.GetInt32(5) : null

where AnswerVal is of type int? and I'm getting the compile-time error

type of conditional expression cannot be determined because because there is no implicit conversion between 'int' and null

Any idea what's going wrong here?

And yes, I've looked at SQL Data Reader - handling Null column values , and I don't understand what I'm doing wrong because my inline if/else is equivalent to the answer there.

You can get the value this way:

int? AnswerVal = !dataReader.IsDBNull(5) ? dataReader.GetInt32(5) : (int?)null; 

There is no implicit conversion between int and null , but there is implicit conversion between int and int? and using (int?)null you are identifying the type of that null.

And of course when the column is defined as not null, you really don't need such check.

According to MSDN

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result. Only one of the two expressions is evaluated. Either the type of first_expression and second_expression must be the same , or an implicit conversion must exist from one type to the other.

In your case the true statement and the false statement are of different types so you need to convert them. As Reza mentioned in the above answer. so the snippet will be :

AnswerVal = !dataReader.IsDBNull(5) ? dataReader.GetInt32(5) : (int?)null; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM