Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "DateTime?" mean in C#?

I am reading a .NET book, and in one of the code examples there is a class definition with this field:

private DateTime? startdate 

What does DateTime? mean?

like image 900
Alvin S Avatar asked Sep 21 '08 00:09

Alvin S


People also ask

What does DateTime mean?

The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. Time values are measured in 100-nanosecond units called ticks.

What is the use of DateTime in C#?

We used the DateTime when there is a need to work with the dates and times in C#. The value of the DateTime is between the 12:00:00 midnight, January 1 0001 and 11:59:59 PM, December 31, 9999 A.D.

Why DateTime is a structure?

The actual data in a DateTime is a single long integer. If it were a class, every time you created a new object, 8 bytes would be allocated on the heap and another 8 bytes would be allocated on the stack for the pointer. So by making a DateTime a struct, it effectively cuts the memory requirements in half.

Is DateTime a value type in C#?

DateTime is a Value Type like int, double etc. so there is no way to assign a null value. When a type can be assigned null it is called nullable, that means the type has no value. All Reference Types are nullable by default, e.g. String, and all ValueTypes are not, e.g. Int32.


2 Answers

Since DateTime is a struct, not a class, you get a DateTime object, not a reference, when you declare a field or variable of that type.

And, in the same way as an int cannot be null, so this DateTime object can never be null, because it's not a reference.

Adding the question mark turns it into a nullable type, which means that either it is a DateTime object, or it is null.

DateTime? is syntactic sugar for Nullable<DateTime>, where Nullable is itself a struct.

like image 173
Thomas Avatar answered Sep 18 '22 13:09

Thomas


It's a nullable DateTime. ? after a primitive type/structure indicates that it is the nullable version.

DateTime is a structure that can never be null. From MSDN:

The DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini, or A.D. (also known as Common Era, or C.E.) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

DateTime? can be null however.

like image 45
Daniel Auger Avatar answered Sep 19 '22 13:09

Daniel Auger