views:

311

answers:

3

What is the difference between a DateTime? and a DateTime (without a question mark) in C#?

+14  A: 

DateTime? can be null as opposed to DateTime

TT
i.e. Nullable<DateTime> - http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx
Russ Cam
Actually, `DateTime?` itself is not null as it is a value type as well. `Nullable<T>` exposes a `HasValue` property that the compiler uses to "fake" reference type semantics on a value type that is wrapped in `Nullable<T>`.
Andrew Hare
+16  A: 

A question mark after a value type is a shorthand notation for the Nullable<T> structure.

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

The Nullable<T> structure allows you to wrap value types (like DateTime, Int32, Guid, etc.) and treat them like reference types in certain respects. It does get a bit more complicated (in terms of assignment, lifted operators, and other things) and as such I would recommend that you read Nullable Types (C# Programming Guide) and its related articles.

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined.

Andrew Hare
+2  A: 

DateTime? is another way of writing Nullable<DateTime>. I suggest you read this to learn more about nullable:

Nullable(T) Structure

apathetic