I ran into an interesting bit of code recently that made use of the FirstOrDefault() method. The original developer had the intention of handling the case where the collection didn’t have a value, but made an incorrect assumption about the return value of FirstOrDefault().

Here’s an example of what was being done:

DateTime? theDate = listOfDates.FirstOrDefault();

if (theDate != null)
{
    //somecode
}

While not immediately obvious, the //somecode block is never reached. I didn’t even realize it at first, at least until I got some strange data on the other end of the method.

So, I learned a little something about nullable types and the default value return by FirstOrDefault().

The default value for FirstOrDefault() does indeed return null for reference types, but nullable types are not reference types; they are structs. For non-reference types (i.e. value types), FirstOrDefault() will return the default value for the type.

In the above example, FirstOrDefault() will return either the first date from the collection, or DateTime.MinValue, which evaluates to 1/1/0001 12:00:00 AM. Since theDate will never be null, the intended block is never reached, and the case is never handled.

Note also that ReSharper will not catch this. The first line is a legal statement (since the value is implicitly converted to a nullable DateTime). But theDate doesn’t even need to be nullable. That line is also valid with a non-nullable DateTime parameter:

DateTime theDate = listOfDates.FirstOrDefault();

Of course, once you change this, ReSharper picks up on the fact that (theDate != null) is always true.

But I still want to handle the intended case, or at least what I assume to be the intended case. The way to do this (while still using FirstOrDefault()) is as follows:

DateTime theDate = listOfDates.FirstOrDefault();

if (theDate != default(DateTime))
{
    //somecode
}