Switch statements with pattern matching

The new switch case statement pattern enhances the case blocks by comparing the value, not just by constants, but also by an expression. In C# 7.0, you can generalize the switch statement in the following manner:

  • You can put switch on any type, in addition to primitive data types
  • You can use patterns on case clauses
  • You can have additional conditions on case clauses using the keyword when

Let's look at the following example, where we have the base Person reference passed to the switch statement:

    public static void Validate(Person person) 
    { 
      switch (person) 
      { 
        case Employee e: 
           Console.WriteLine($"{e.Firstname} is an Employee"); 
           break; 
 
        case Customer c when (c.IsPremium): 
           Console.WriteLine($"{c.Firstname} is a Premium Customer"); 
           break; 
 
        case Customer c: 
           Console.WriteLine($"{c.Firstname} is a Customer"); 
           break; 
 
        default: 
           Console.WriteLine($"{person.Firstname} is a Person"); 
           break; 
 
        case null: 
           Console.WriteLine("Null value specified
"); 
           break; 
      } 
    } 
 
    // satisfies the first case of type Employee 
    Validate(new Employee { Firstname = "Kunal" }); 
 
    // satisfies the second case where the person is a Premium Customer 
    Validate(new Customer { Firstname = "Kunal", IsPremium = true }); 
 
    // satisfies the third case where the person is a Normal Customer 
    Validate(new Customer { Firstname = "Kunal" }); 
 
    // satisfies the fourth case where the person does not fit any of the above cases 
    Validate(new Person { Firstname = "Kunal" }); 
 
    // satisfies the fifth case when the person is set as 'null'  
    Validate(null); 

In this example, if the person is an Employee, the first case clause will execute. When the person is a Customer, the second or third case clause will execute based on the condition satisfied by the when expression. If no other case satisfies, it will execute the default case.

When the object passed to the switch statement is null, it will get higher preference on top of the default case, jump directly to the case null, and display Null value specified in the console window. This will reduce your additional code to checking whether the object is null and giving you the option to handle the null check within the switch case:

Some important points on switch statements in C# 7.0:

  • Just like the catch clauses, the order of the case clauses now matters. The first clause that matches, gets picked. For example, the first clause of the following code snippet gets picked up when a customer is a premium user. This is a valid case for the compiler:
  • The following case becomes invalid as the more generic one gets picked up before checking the condition within the case statement. The compiler will give an error in such cases, as it has already been handled by the previous case:
  • Also, the compiler will give you an error for such obvious cases having unreachable codes. The following code snippet is invalid as well:
  • Even though you write the null case at the end, the default case always gets evaluated at the end, giving higher preference to the null check.
  • The pattern variables introduced by a case are always in the scope of the corresponding switch section only.

Visual Studio 2015 and C# 6.0 included a similar kind of when-clause pattern as part of a structured error handling system:

    try 
    { 
      // perform your error prone code 
    } 
    catch (Exception ex) when (logExceptionDetails) 
    { 
      // handle the exception only if you want to log 
      Console.WriteLine("Catch block when logExceptionDetails=true"); 
    } 
    catch 
    { 
      // all other cases 
      Console.WriteLine("Catch block when logExceptionDetails=false"); 
    } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.133.96