[Solved] What’s the point of variables in C# 7.0’s pattern matching?


What’s the point of “s”?

It’s a variable of the type that you’ve just checked for, which you often want to use.

Your example is an unfortunate one as Console.WriteLine accepts object as well… but suppose you wanted to print out the length of the string. Here’s a complete example without pattern matching:

public void PrintLengthIfString(object obj)
{
    if (obj is string)
    {
        string str = (string) obj;
        Console.WriteLine(str.Length);
    }
}

It’s not only longer, but it’s performing the same check twice, effectively: once for the is operator, and once for the cast. Pattern matching make this simpler, by getting the value of the string as part of the is operator:

public void PrintLengthIfString(object obj)
{
    if (obj is string str)
    {
        // No cast here, it's in the pattern match!
        Console.WriteLine(str.Length);
    }
}

solved What’s the point of variables in C# 7.0’s pattern matching?