0

I have to do a c# search on records in an array from a sql server db using 3 data elements. One of the data elements has to be a DateTime element in a column called DateOfBirth. Unfortunately there are a lot of null values in this column and I can't figure out how to compare a DateTime variable to a field with NULL values. I see a lot of answers that appear to be close to what I need here, but nothing has helped. Thanks for any help, This has been my format.

if ((DateTime)dt == (DateTime)temp[i].Individual.DateOfBirth)
    GlobalNum3.bnum3 = 1;
2
  • 1
    So what happens with this code? Do you get a NullReferenceException? What are the compile time types of dt and DateOfBirth? Commented May 31, 2015 at 19:35
  • would it be an option to alter the SQL query so that entries with NULL datetimes are excluded? You could then process those entries in a seperate method. Something like ...WHERE DateOfBirth IS NOT NULL [...] would do the job. Commented May 31, 2015 at 19:45

2 Answers 2

1

I'm assuming that dt is already a DateTime, in which case it can't be null (DateTime is a struct) and there's no need to cast it.In addition, either temp[i].Individual.DateOfBirth is a DateTime too and so cannot be null either, or it's a Nullable<DateTime>.

Assuming both are DateTimes, DB nulls will be set to DateTime.MinValue, so just compare the values:

if (dt == (DateTime)temp[i].Individual.DateOfBirth)
{
    GlobalNum3.bnum3 = 1;
}

However, if temp[i].Individual.DateOfBirth is a Nullable<DateTime>, it might be null, or might simply have no value, so use it like this:

var possibleDateOfBirth = temp[i].Individual.DateOfBirth;
if (possibleDateOfBirth != null &&
    possibleDateOfBirth.HasValue &&
    dt == possibleDateOfBirth.Value)
{
    GlobalNum3.bnum3 = 1;
}
Sign up to request clarification or add additional context in comments.

4 Comments

A DateTime in .NET can't be null. It's DateTime.MinValue. (DateTime is a struct type).
@SteffenWinkler, yep, that's what I said "I'm assuming that dt is already a DateTime, in which case it can't be null"
in that case I don't get your if statement :/
@SteffenWinkler, hmm, I see what you mean. I only half thought through the DateTimes. temp[i].Individual.DateOfBirth either is a DateTime and so can't be null or must be a Nullable<DateTime>. I'll update the answer.
0

If you are querying the DB then try testing the nullable .HasValue property like this:

if (temp[i].Individual.DateOfBirth.HasValue && dt == temp[i].Individual.DateOfBirth.Value)
{
   GlobalNum3.bnum3 = 1;
}

Obviously I'm assuming you are testing DateTime? properties.

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.