Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 245
Rich Avatar asked Jul 06 '11 15:07

Rich


People also ask

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

How do I know if the DateTime is not null?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.

Can we assign null to DateTime in C#?

CSharp Online TrainingUsing the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax.

Should DateTime be nullable?

DateTime itself is a value type. It cannot be null. Show activity on this post. No -- DateTime is a struct in C# and structs (value types) can not be null.


1 Answers

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?.

like image 151
Henk Holterman Avatar answered Oct 08 '22 17:10

Henk Holterman