How to check for default DateTime value?

C#.NetDesign Patterns

C# Problem Overview


I need to check a DateTime value if it has a value or not.

I have several options:

if (dateTime == default(DateTime))

or

if (dateTime == DateTime.MinValue)

or using a nullable DateTime?

if (nullableDateTime.HasValue)

Personally I would prefer the third version, since its pretty good readable. But in our database we have some datetime columns which are defined as not null. So in some cases I have to go with the first two options.

I read somewhere that the default keyword should be used when working with generics, but isn't it much more readable in this case? When using the second option I have to know that the default value of a new and empty DateTime instance is DateTime.MinValue which has the smell of an implementation detail for me.

So which option should I use to use "best practice"?

C# Solutions


Solution 1 - C#

I would probably make this really explicit:

// Or private, or maybe even public
internal static readonly DateTime MagicValueForNullDateTimeInNonNullableColumns
    = DateTime.MinValue;

Okay, so I'd make the name slightly less wordy, but you get what I mean. It doesn't really matter much how you initialize that value - it's clear what you're trying to do.

(Of course, use a nullable type any time you can for this. I'm assuming the question was asked because you couldn't do so in certain situations.)

Solution 2 - C#

> I need to check a DateTime value if it has a value or not.

You've pretty-much described the textbook situation requiring a Nullable<DateTime>. I'd go with that option.

(You'd obviously need some sort of translation layer if you need to persist the values to a non-null db column, but I'd try to keep any "magic" value as close to the db as possible, and try to keep your C# code clean and idiomatic.)

Solution 3 - C#

The "best" practice would be using the nullable DateTime. Nullable value types were created exactly for that reason of not trusting "magic" numbers.

What's most important about this approach is its intent - what does it mean in your context to have a "default" date/time?

Solution 4 - C#

Maybe you can set a default value in your database with getdate() and then update all null values to min value or whatever you like. At least you will have one condition

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondasheddotView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#LukeHView Answer on Stackoverflow
Solution 3 - C#Igal TabachnikView Answer on Stackoverflow
Solution 4 - C#KuzgunView Answer on Stackoverflow