user979331
user979331

Reputation: 11951

Using DateTime with Null

I have this line of code here:

command.Parameters["@DateCompleted"].Value = items[i].DateCompleted.Equals("01/01/0001 12:00:00 AM") ? null : items[i].DateCompleted;

but I got this error:

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'

What I am trying to do is not use the 01/01/0001 Date and use null because the item is null.

Additional Code:

command.Parameters.Add("@DateCompleted", System.Data.SqlDbType.DateTime);

Upvotes: 0

Views: 293

Answers (3)

Nicholas Petersen
Nicholas Petersen

Reputation: 9578

To use the ternary operator where one of the return types is null, the other return type has to be a nullable type, which DateTime is not, being a struct. What you could do is replace the null with default(DateTime):

DateTime value = someCondition ? default(DateTime) : items[i].DateCompleted;

Upvotes: 0

Donald.Record
Donald.Record

Reputation: 301

Use DateTime?

command.Parameters["@DateCompleted"].Value = items[i].DateCompleted.Equals("01/01/0001 12:00:00 AM") ? (DateTime?)null : items[i].DateCompleted;

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241858

Simply cast the null to a DateTime?. Also, assuming DateCompleted is a DateTime (it should be), then don't compare against a string, but against DateTime.MinValue instead.

command.Parameters["@DateCompleted"].Value =
    items[i].DateCompleted.Equals(DateTime.MinValue) 
        ? (DateTime?) null
        : items[i].DateCompleted;

Upvotes: 6

Related Questions