Now from C# 7.0 Switch statement will be having more power in matching the cases. Earlier, Switch statement can be used only for primitive and string types. But now we can even use the Switch statements one step ahead for object types. 

We will see a simple example which demonstrates what we are taking till now.

public void SwitchDemo() 
 { 
     object obj = new Dog() { Name = "Dog" }; 
  
     switch(obj) 
     { 
         case Dog dog: Console.WriteLine(dog.Name); break; 
         case Cat cat: Console.WriteLine(cat.Name); break; 
         case null: Console.WriteLine("Not Assign"); break; 
         default: Console.WriteLine("No match found"); break; 
     } 
 }

In the above code, you can see we are trying to send an object to the Switch statement and finding the type of it in the case. At case, we are using pattern matching feature where internally it will do an is-Expression and match the type to select the appropriate type.

We also having a null case, as when given object is null, it won’t match with the type (Please read more about Pattern Matching here).

Addition to this, from C# 7.0, it allows even to perform some logical expressions at the case level. Let we extend the above sample to demonstrate it. Here we are trying to set an additional condition to each case where it should satisfy type as well as Name. For this, we need to use when keyword as follows.

public void SwitchDemoWithCondition() 
{ 
    object obj = new Dog() { Name = "Dog" }; 
  
    switch (obj) 
    { 
        case Dog dog when dog.Name == "Dog": Console.WriteLine(dog.Name); break; 
        case Dog dog when dog.Name == "Doggy": Console.WriteLine(dog.Name); break; 
        case Cat cat: Console.WriteLine(cat.Name); break; 
        case null: Console.WriteLine("Not Assign"); break; 
        default: Console.WriteLine("No match found"); break; 
    } 
}

Can observe the first two statements in the above sample, where we even added an additional condition of Name using when keyword. 

Note: Here case Ordering is mandatory. From top to bottom, the first match will be selected as a match.

Hope, this explanation gives you the concept.

You can see complete code here in GitHub

Happy Coding 🙂