12

I've got a nullable datetime object in C#.

DateTime? StartDate = new DateTime();

I then check a user submitted value to determine if a date is applicable to this record:

if (Complete == "N/A")
{
    StartDate = null;
}

Now I come to my query which may or may not be inserting a null datetime:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = StartDate;
}

As you'd probably expect if the start date is null then I get an error that the type is not correct. What's the best way to proceed from here?

I have considered checking startdate is null but am not sure how to do that when the type is nullable.

deed02392
  • 4,799
  • 2
  • 31
  • 48
  • 1
    As an aside, you can easily check if a nullable type is null in two ways. 1) `!StartDate.HasValue`, or 2) Simply `StartDate == null` – Ray Feb 01 '12 at 16:19

2 Answers2

19

This will pass a database NULL value as the parameter if StartDate is null:

using (SqlCommand command = new SqlCommand(updateSql, db))
{
    command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value = (object)StartDate ?? DBNull.Value;
}
Roy Goode
  • 2,940
  • 20
  • 22
2
using (SqlCommand command = new SqlCommand(updateSql, db))
{
    if (StartDate.HasValue())
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value
            = StartDate;
    else
        command.Parameters.Add("@Date_Started", SqlDbType.DateTime).Value 
            = DBNull.Value;
}
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108