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

后端 未结 2 2007
[愿得一人]
[愿得一人] 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:31

    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.

提交回复
热议问题