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"?
The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).
SYSDATETIME() will get the current date and time. Make sure the data type of the column is datetime , and not just date or it won't be able to hold a datetime. Show activity on this post. Most SQL implementations (engines) do have CURRENT_TIMESTAMP function.
If you are using DateTime then DateTime dat = new DateTime();if (dat==DateTime. MinValue){//unassigned datetime}Or if you are using nullable DateTime then DateTime? dat = null;if (!
The value of this constant is equivalent to 00:00:00.0000000 UTC, January 1, 0001, in the Gregorian calendar. MinValue defines the date and time that is assigned to an uninitialized DateTime variable.
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.)
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With