Search code examples
c#sqlnullabledbnull

How to read null for null-able Boolean values


I am trying to read nullable values from a database. Right now my code is converting null values to false. How can I modify my code to allow for null values?

Ap1ExamTaken = dr["AP1_ExamTaken"] != DBNull.Value && Convert.ToBoolean(dr["AP1_ExamTaken"]),

I would like values that are null to be shown as null and not false.


Solution

  • You could use the conditional operator here, to set it to null if the value is DBNull.Value, or a non-nullable value otherwise:

    Ap1ExamTaken = dr["AP1_ExamTaken"] == DBNull.Value ? null : (bool?) dr["AP1_ExamTaken"];
    

    Note that this will throw an exception if dr["AP1_ExamTaken"] is a non-boolean, non-DBNull type, which I suspect is what you want.

    You could write it more compactly as:

    Ap1ExamTaken = dr["AP1_ExamTaken"] as bool?
    

    ... but then you'll end up with a null value if the value is some other type (a string, an integer etc) which I'd generally be alarmed about. (If my data doesn't have the shape I expect, I want to know ASAP.)