From 7ea5810a8acc055c42b0b05e6d09c917487e94bc Mon Sep 17 00:00:00 2001 From: Marcin Grygierczyk Date: Thu, 22 Nov 2018 13:57:49 +0100 Subject: [PATCH] Add description of when clause (#22464) --- guide/english/csharp/switch-case/index.md | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/guide/english/csharp/switch-case/index.md b/guide/english/csharp/switch-case/index.md index 3b8d9ff327..38152efadf 100644 --- a/guide/english/csharp/switch-case/index.md +++ b/guide/english/csharp/switch-case/index.md @@ -60,5 +60,44 @@ switch(myColor) { ``` This will execute the same lines of code if myColor is either Red or Blue. +## When clause + +Starting with C# 7.0 you can use `when` clause to specify additional condition that must be satisfied. When clause is optional and is used right after specific case. + +```csharp +Dog dog = new Dog +{ + Name = "Charlie", + Breed = "Affenpinscher", + Age = 3 +}; + +switch (dog) +{ + case Dog d when d.Breed == "Affenpinscher" && d.Age >= 6: + Console.WriteLine($"{dog.Name} is considered a senior dog."); + break; + case Dog d when d.Breed == "Affenpinscher" && d.Age >= 2: + Console.WriteLine($"{dog.Name} is considered an adult dog."); + break; + case Dog d when d.Breed == "Affenpinscher": + Console.WriteLine($"{dog.Name} is considered a puppy."); + break; + case Dog d when d.Breed == "Chihuahua" && d.Age >= 4: + Console.WriteLine($"{dog.Name} is considered a senior dog."); + break; + case Dog d when d.Breed == "Chihuahua" && d.Age >= 2: + Console.WriteLine($"{dog.Name} is considered an adult dog."); + break; + case Dog d when d.Breed == "Chihuahua": + Console.WriteLine($"{dog.Name} is considered a puppy."); + break; + default: + Console.WriteLine($"We have no information according {dog.Breed} breed."); + break; +} +``` +As you see in the above example after `when` keyword you should specify logical condition (an instruction that returns bool value). + ### Sources: - 1 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch