Using the keyword "is" with the keyword "null" C # 7.0

I recently found out that the following code compiles and works as expected in VS2017. But I can not find the topic / documentation on this. So I'm curious if using this syntax is correct:

class Program
{
    static void Main(string[] args)
    {
        var o = new object();              
        Console.WriteLine(o is null);
        o = null;
        Console.WriteLine(o is null);
        Console.ReadLine();
    }
}

By the way, this does not work in VS2015

+4
source share
2 answers

Yes, that is absolutely true. This uses the C # 7 pattern matching function, which is available with isand expressions switch/case. (The fact that it requires C # 7, why it doesn't work for you in VS2015.) For example:

// Type check, with declaration of new variable
if (o is int i)
{
    Console.WriteLine(i * 10);
}
// Simple equality check
if (o is 5)  {}

, , null, is, /:

switch (o)
{
    case int i when i > 100000:
        Console.WriteLine("Large integer");
        break;
    case null:
        Console.WriteLine("Null value");
        break;
    case string _:
        Console.WriteLine("It was a string");
        break;
    default:
        Console.WriteLine("Not really sure");
        break;
}

# 7 . MSDN Mads Torgersen.

+13

, o null, o == null.

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

IL.

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

, :

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

, o null

Object.Equals(value, null);

, o null o == null . . ! , .

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

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

, 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

, == TestObject, . o null o == null . , - .

+6

Source: https://habr.com/ru/post/1674374/


All Articles