Reputation: 2966
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"?
Upvotes: 72
Views: 137380
Reputation: 1500675
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.)
Upvotes: 84
Reputation: 4737
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
Upvotes: 0
Reputation: 31548
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?
Upvotes: 9
Reputation: 269388
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.)
Upvotes: 20