If a DateTime object cannot be null, what is it before it is assigned?

It will probably hold the value of DateTime.MinValue (The value of this constant is equivalent to 00:00:00.0000000, January 1, 0001.)


A DateTime variable is by default DateTime.MinValue if you did not assign it another value http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx


It will be default(DateTime) which by a design-decision happens to be DateTime.MinValue

default(T) is what types are initialized to when used as fields or array members.
default(int) == 0, default(bool) == false etc.
The default for all reference types is of course null.

It is legal to write int i = default(int); but that's just a bit silly. In a generic method however, T x = default(T); can be very useful.

surely it is massively illogical that such a reference could be null, but not assigned null?

DateTime is a Value-type, (struct DateTime { ... }) so it cannot be null. Comparing it to null will always return false.

So if you want find out the assigned status you can compare it with default(DateTime) which is probably not a valid date in your domain. Otherwise you will have to use the nullable type DateTime?.

Tags:

C#