Search code examples
c#datetimetype-conversiondbnull

How to convert a value if it's null


I am using C#

Convert.ToDateTime(rdr["Termination_Date"])

rdr is defined as

OracleDataReader rdr = cmd.ExecuteReader();

The Termination_Date field in the table maybe null. How do I check if it's null and set a date like 01/01/0001


Solution

  • If you have to access the column by name, you can compare against DBNull.Value with something like a ternary statement to pick between DateTime.MinValue (1/1/0001) and the result of converting the non-null value.

    OracleDataReader rdr = cmd.ExecuteReader();
    
    DateTime terminationDate = rdr["Termination_Date"] == DBNull.Value
        ? DateTime.MinValue
        : Convert.ToDateTime(rdr["Termination_Date"]);
    

    You can do this more concisely with OracleDataReader.IsDBNull() and OracleDataReader.GetDateTime() if you know the column index (assume that our desired value is the first column in the result).

    OracleDataReader rdr = cmd.ExecuteReader();
    
    DateTime terminationDate = rdr.IsDBNull(0)
        ? DateTime.MinValue
        : rdr.GetDateTime(0);