Bohn
Bohn

Reputation: 26919

Possible InvalidOperationException when working with Nullable DateTime in LINQ

I have some variable defined like this:

DateTime? tempDateTime;

and also I have a query like this:

var recordWithMinDatetime =
    locatedContracts.Where(t => t.OriginalDate.HasValue)
        .OrderBy(t => t.OriginalDate.Value)
        .FirstOrDefault();
    if (recordWithMinDatetime != null)
        tempDateTime = recordWithMinDatetime.OriginalDate.Value;

But in the IDE when I hover over the last assignment, it says "Possible InvalidOperationException"

I have ReSharper installed too, so not sure if it is from R# or VS IDE but still something I should concern about I think but I don't understand what is it I have done wrong or non-safe code that it gives me this hint?

Upvotes: 1

Views: 1153

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

That's likely a R# error. I would ignore it. You've ensured that OriginalDate.Value won't throw an exception by checking HasValue in your LINQ query.

R# is trying to be helpful, and probably expects a check like this:

if (recordWithMinDatetime != null && recordWithMinDatetime.OriginalDate.HasValue)
    tempDateTime = recordWithMinDatetime.OriginalDate.Value;

But in your case, this check is redundant.

Upvotes: 6

Related Questions