Set an empty DateTime variable
Since DateTime
is a value type you cannot assign null
to it, but exactly for these cases (absence of a value) Nullable<T>
was introduced - use a nullable DateTime
instead:
DateTime? myTime = null;
No. You have 2 options:
DateTime date = DateTime.MinValue;
This works when you need to do something every X amount of time (since you will always be over MinValue
) but can actually cause subtle errors (such as using some operators w/o first checking if you are not MinValue
) if you are not careful.
And you can use Nullable
:
DateTime? date = null;
Which is nice and avoids most issues while introducing only 1 or 2.
It really depends on what you are trying to achieve.
You can set a DateTime variable to be '1/1/0001 00:00:00' but the variable itself cannot be null. To get this MinTime use:
DateTime variableName = DateTime.MinValue;