I need to know is there a difference between
DateTime? obj
And
Nullable<DateTime> obj
If it is the case, what are their use cases?
I need to know is there a difference between
DateTime? obj
And
Nullable<DateTime> obj
If it is the case, what are their use cases?
There is no difference. The former is syntactic sugar for the second. They compile to the exact same thing, Nullable<DateTime>
, building identical IL.
void Main()
{
DateTime? test1 = DateTime.Now;
Nullable<DateTime> test2 = DateTime.Now;
}
IL for DateTime?
IL_0001: ldloca.s 00 // test1
IL_0003: call System.DateTime.get_Now
IL_0008: call System.Nullable<System.DateTime>..ctor
IL for Nullable<DateTime>
IL_000E: ldloca.s 01 // test2
IL_0010: call System.DateTime.get_Now
IL_0015: call System.Nullable<System.DateTime>..ctor
There is no difference. DateTime?
is a shorter way of writing Nullable<DateTime>
. The actual type is Nullable<DateTime>
As MSDN suggests:
The syntax T? is shorthand for Nullable{T}, where T is a value type. The two forms are interchangeable.
There is no difference, as you can see in the following decompiled MSIL code:
when this is the original source:
static void Main(string[] args)
{
DateTime? time = null;
Nullable<DateTime> obj = null;
if (false)
{
Console.WriteLine(time + " " + obj);
}
}
both compile to Nullable<DateTime>
. DateTime?
is just a syntax sugar.
From MSDN:
Nullable types can represent all the values of an underlying type, and an additional null value. Nullable types are declared in one of two ways:
System.Nullable<T> variable
-or-
T? variable
Meaning they are equivalents. This behaviour however is not specific for type DateTime
but for any other valuetype.