What is the difference between a DateTime?
and a DateTime
(without a question mark) in C#?
views:
311answers:
3A 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, aNullable<Int32>
, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. ANullable<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.
DateTime? is another way of writing Nullable<DateTime>. I suggest you read this to learn more about nullable: