C# 7 and .NET Core 2.0 Blueprints
上QQ阅读APP看书,第一时间看更新

Pattern matching

Staying with the PopulateStorageSpacesList() method, we can see the use of another C# 7 feature called pattern matching. The spaces is null line of code is probably the simplest form of pattern matching. In reality, pattern matching supports several patterns.

Consider a switch statement:

switch (objObject) 
{ 
    case null: 
        WriteLine("null"); // Constant pattern 
        break; 
 
    case Document doc when doc.Author.Equals("Stephen King"): 
        WriteLine("Stephen King is the author"); 
        break; 
 
    case Document doc when doc.Author.StartsWith("Stephen"): 
        WriteLine("Stephen is the author"); 
        break; 
 
    default: 
        break; 
} 

Pattern matching allows developers to use the is expression to see whether something matches a specific pattern. Bear in mind that the pattern needs to check for the most specific to the most general pattern. If you simply started the case with case Document doc: then all the objects passed to the switch statement of type Document would match. You would never find specific documents where the author is Stephen King or starts with Stephen.

For a construct inherited by C# from the C language, it hasn't changed much since the '70s. C# 7 changes all that with pattern matching.