Why it is not allowed to assign null to a DateTime in C#? How has this been implemented? And can this feature be used to make your own classes non-nullable?
Example:
string stringTest = null; // Okay DateTime dateTimeTest = null; // Compile error
I know that I can use DateTime?
in C# 2.0 to allow null to be assigned to dateTimeTest and that I could use Jon Skeet's NonNullable class on my string to get a run time error on the assignment of stringTest. I'm just wondering why the two types behave differently.
Yes, that works fine.
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.
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
is a value-type (struct
), where-as string is a reference-type (class
etc). That is the key difference. A reference can always be null; a value can't (unless it uses Nullable<T>
- i.e. DateTime?
), although it can be zero'd (DateTime.MinValue
), which is often interpreted as the same thing as null (esp. in 1.1).
DateTime is a struct and not a class. Do a 'go to definition' or look at it in the object browser to see.
HTH!
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