views:

3933

answers:

5

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?

+9  A: 

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 (Common Era) to 11:59:59 P.M., December 31, 9999 A.D. (C.E.)

DateTime? can be null however.

Daniel Auger
+3  A: 

It's equivalent to Nullable< DateTime>. You can append "?" to any primitive type or struct.

Ted Elliott
+24  A: 

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 can this DateTime object 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.

Thomas
+5  A: 

A ? as a suffix for a value type allows for null assignments that would be othwerwise impossible.

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

Represents an object whose underlying type is a value type that can also be assigned a null reference.

This means that you can write something like this:

    DateTime? a = null;
    if (!a.HasValue)
    {
        a = DateTime.Now;
        if (a.HasValue)
        {
            Console.WriteLine(a.Value);
        }
    }

DateTime? is syntatically equivalent to Nullable<DateTime>.

smink
+3  A: 

it basically gives you an extra state for primitives. It can be a value, or it can be null. It can be usefull in situations where a value does not need to be assigned. So rather than using for example, datetime.min or max, you can assign it null to represent no value.

mattlant