Using "is" keyword with "null" keyword c# 7.0

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 this syntax:

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();
    }
}

BTW this is not working in VS2015

Jon Skeet
people
quotationmark

Yes, it's entirely valid. This uses the pattern matching feature of C# 7, which is available with is expressions and switch/case statements. (The fact that it requires C# 7 is why it isn't working 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)  {}

Equality checks like the latter - particularly for null - aren't likely to be very useful for is pattern matching, but are more useful for switch/case:

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;
}

For more details of C# 7 features, see the MSDN blog post by Mads Torgersen.

people

See more on this question at Stackoverflow