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?
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.
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
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.
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.
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?
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With