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.
DateTimeis a value-type (struct), where-as string is a reference-type (classetc). That is the key difference. A reference can always be null; a value can’t (unless it usesNullable<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).