C# – Difference Between myNullableLong.HasValue and myNullableLong != null

c++nullable

When I have a nullable long, for example, is there any difference between

myNullableLong.HasValue 

and

myNullableLong != null

… or is it just 'syntactic sugar'?

Best Answer

It's just syntactic sugar. They will behave exactly the same way - the nullity test actually gets compiled into a call to HasValue anyway.

Sample:

public class Test
{
    static void Main()
    {
        int? x = 0;
        bool y = x.HasValue;
        bool z = x != null;
    }
}

IL:

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       25 (0x19)
  .maxstack  2
  .locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
  IL_0000:  ldloca.s   V_0
  IL_0002:  ldc.i4.0
  IL_0003:  call       instance void valuetype [mscorlib]System.Nullable`1<int32>::.ctor(!0)
  IL_0008:  ldloca.s   V_0
  IL_000a:  call       instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_000f:  pop
  IL_0010:  ldloca.s   V_0
  IL_0012:  call       instance bool valuetype [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_0017:  pop
  IL_0018:  ret
} // end of method Test::Main
Related Question