Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is null not allowed for DateTime in C#?

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.

like image 805
Jan Aagaard Avatar asked Mar 27 '09 12:03

Jan Aagaard


People also ask

Can date data type be null?

Yes, that works fine.

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.

How do you check if a DateTime variable is 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.


2 Answers

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

like image 106
Marc Gravell Avatar answered Sep 20 '22 02:09

Marc Gravell


DateTime is a struct and not a class. Do a 'go to definition' or look at it in the object browser to see.

HTH!

like image 35
Simon Avatar answered Sep 21 '22 02:09

Simon