Switch Statement Enhancements In C# 7.0

From C# 7.0, the Switch statement has been enabled with more power in matching the cases. Earlier, the Switch statement could 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 talking about.

  1. public void SwitchDemo() {  
  2.     object obj = new Dog() {  
  3.         Name = "Dog"  
  4.     };  
  5.     switch (obj) {  
  6.         case Dog dog:  
  7.             Console.WriteLine(dog.Name);  
  8.             break;  
  9.         case Cat cat:  
  10.             Console.WriteLine(cat.Name);  
  11.             break;  
  12.         case null:  
  13.             Console.WriteLine("Not Assign");  
  14.             break;  
  15.         default:  
  16.             Console.WriteLine("No match found");  
  17.             break;  
  18.     }  
  19. }  

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. In the case statement, 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 have a null case. This works when a given object is null. It won't match with the type.

Now, in C# 7.0, it allows for performing some logical expressions at the case level. Let us extend the above sample to demonstrate it. Here, we are trying to set an additional condition to each case where it should satisfy the type as well as the Name. For this, we need to use the when keyword as below. 

  1. public void SwitchDemoWithCondition() {  
  2.     object obj = new Dog() {  
  3.         Name = "Dog"  
  4.     };  
  5.     switch (obj) {  
  6.         case Dog dog when dog.Name == "Dog":  
  7.             Console.WriteLine(dog.Name);  
  8.             break;  
  9.         case Dog dog when dog.Name == "Doggy":  
  10.             Console.WriteLine(dog.Name);  
  11.             break;  
  12.         case Cat cat:  
  13.             Console.WriteLine(cat.Name);  
  14.             break;  
  15.         case null:  
  16.             Console.WriteLine("Not Assign");  
  17.             break;  
  18.         default:  
  19.             Console.WriteLine("No match found");  
  20.             break;  
  21.     }  
  22. }  

We can observe the first two statements in the above sample where we have added an additional condition of Name using when keyword.  

Note
Here, the case ordering is mandatory. 

Hope, this explanation gives you the concept. 

You can see complete code here on GitHub.

Happy Coding :)