Using “is” keyword with “null” keyword c# 7.0

后端 未结 2 1995
[愿得一人]
[愿得一人] 2020-12-17 16:49

Recently i find out, that the following code compiles and works as expected in VS2017. But i can\'t find any topic/documentation on this. So i\'m curious is it legit to use

2条回答
  •  一整个雨季
    2020-12-17 17:20

    Yes, it is valid to write o is null, but this is not equivalent to o == null. The code

    static bool TestEquality(object value) => value == null;
    

    compiles into following IL instructions.

      IL_0000:  ldarg.0
      IL_0001:  ldnull
      IL_0002:  ceq
      IL_0004:  ret
    

    The pattern matching case compiled in following manner:

    static bool TestPatternMatching(object value) => value is null;
    
      IL_0000:  ldnull
      IL_0001:  ldarg.0
      IL_0002:  call       bool [System.Runtime]System.Object::Equals(object, object)
      IL_0007:  ret
    

    So, pattern matching o is null is equivalent to

    Object.Equals(value, null);
    

    So, in most cases o is null and o == null will behave in same way. Except equality variant is a bit faster. BUT! Things will change dramatically, if we replace object with following class.

    class TestObject
    {
        public static bool operator ==(TestObject lhs, TestObject rhs) => false;
        public static bool operator !=(TestObject lhs, TestObject rhs) => false;
    }
    

    and methods with

    static bool TestEquality(TestObject value) => value == null;
    static bool TestPatternMatching(TestObject value) => value is null;
    

    The pattern matching will stay same, but the equality variant will use following IL

      IL_0000:  ldarg.0
      IL_0001:  ldnull
      IL_0002:  call       bool PatternMatchingTest.TestObject::op_Equality(class PatternMatchingTest.TestObject, class PatternMatchingTest.TestObject)
      IL_0007:  ret
    

    Here we can see, that == operator is using TestObject's overload as expected. But o is null and o==null will give different results. So be careful using pattern matching is operator.

提交回复
热议问题