If a DateTime instance has not been assigned yet, what is it's value?
To look at a specific example: In the class below, would "UnassignedDateTime==null" return true?
And if so, surely it is massively illogical that such a reference could be null, but not assigned null?
class TestClass
{
public DateTime AssignedDateTime {get; set;}
public Date开发者_开发问答Time UnassignedDateTime {get; set;}
public TestClass()
{
AssignedDateTime=DateTime.Now;
//Not assigning other property
}
}
I've already checked this answer to a similar question, but it's about DateTime? which is nullable.. How to check if DateTime object was not assigned?
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?
.
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 probably hold the value of DateTime.MinValue
(The value of this constant is equivalent to 00:00:00.0000000, January 1, 0001.)
A DateTime
will be at it's minimum value if it's initalized, but not set. e.g. 12:00:00 midnight, January 1, 0001
Can't check right now but I think it defaults to: 01/01/0001 00:00:00.
If you debugged your code and hovered over the property it should tell you.
The other possibility is MinValue
, which I think is what it is initially. Because is it stored as an integer internally, that would make sense.
Since DateTime
is a struct it is not nullable (DateTime?
), the condition UnassignedDateTime == null
is always false.
精彩评论