-3

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?

Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191

4 Answers4

8

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
David L
  • 32,885
  • 8
  • 62
  • 93
4

There is no difference. DateTime? is a shorter way of writing Nullable<DateTime>. The actual type is Nullable<DateTime>

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
1

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:

Nullables

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.

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
1

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.

Grundy
  • 13,356
  • 3
  • 35
  • 55
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111