Is there any difference between myNullableLong.HasValue and myNullableLong != null?

人盡茶涼 提交于 2019-11-30 04:40:56

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

It's syntactic sugar; Nullable<T> is actually a struct, so it cannot actually be null; the compiler turns calls that compare to null (like your second example) into calls to HasValue.

Note, though, that boxing a Nullable<T> into an object will result in either the value of T (if it has a value) or null (if it doesn't).

I.E.

int? foo = 10; // Nullable<int> with a value of 10 and HasValue = true
int? bar = null; // Nullable<int> with a value of 0 and HasValue = false

object fooObj = foo; // boxes the int 10
object barObj = bar; // boxes null

Console.WriteLine(fooObj.GetType()) // System.Int32
Console.WriteLine(barObj.GetType()) // NullReferenceException
SLaks

No.

The C# compiler has built-in support for Nullable<T> and will turn equality operations involving null into calls to the struct's members.

n != null and n.HasValue will both compile to identical IL.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!