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 ...

Get C# 7 and .NET Core 2.0 Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.