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.
- 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. 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.
- 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;
- }
- }
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 :)