2

Having an issue with casting a datetime from a reader where the value is null.

form._date101 = reader[52] == DBNull.Value ? DBNull.Value : (DateTime?)reader[52];

getting: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'System.DateTime?'

any ideas?

2
  • You could probably discombobulate yourself if you broke that into two lines. Commented May 9, 2013 at 19:50
  • The two expressions which can be returned must be the same type. Your first possibility is returning a DBNull type, and the next is returning a DateTime? type. Commented May 9, 2013 at 20:13

2 Answers 2

12

I suspect you meant:

form._date101 = reader[52] == DBNull.Value ? null : (DateTime?)reader[52];

That's assuming that _date101 is a field of type DateTime?. I expect you want to say "Use the null value of DateTime? if the value was null in the database; otherwise use the non-null value.

Sign up to request clarification or add additional context in comments.

Comments

2

You can also take Jon's answer and add it as an extension method like this:

public static class ReaderExtensions
{
    public static DateTime? GetNullableDateTime(this SqlDataReader reader, string name) =>
        reader[name] == DBNull.Value ? (DateTime?)null : (DateTime?)reader[name];
}

Then you can use it like this:

item.PatientDob = reader.GetNullableDateTime("Birth_Dt");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.