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 DateTime 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 beDateTime.MinValuedefault(T)is what types are initialized to when used as fields or array members.default(int) == 0,default(bool) == falseetc.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.DateTime is a Value-type, (
struct DateTime { ... }) so it cannot benull. 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 typeDateTime?.