Sometimes we want to use switch
statements but the cases are more complex than constants. With a C# when
-clause, we can make a case statement more restricted.
Consider a program that wants to treat a number differently based on whether a bool
is set to true or false. We can place a boolean expression in a when
-clause.
This example C# program wants to test the count variable for a value greater than 10. It has separate logic for when the valid bool
is set to true or false.
bool
is set to false, the second case is matched. The first case is skipped over.using System; // Use when keyword in switch. int count = 20; bool valid = false; switch (count) { case > 10 when valid: Console.WriteLine("Greater than 10 and valid!"); break; case > 10 when !valid: // This is reached because valid is false. Console.WriteLine("Greater than 10 and not valid"); break; case < 0 when valid: Console.WriteLine("Negative and valid"); break; default: Console.WriteLine("Other"); break; }Greater than 10 and not valid
Suppose we want to match all values higher than a number, with one excepted value, in a switch
expression. We can do this with an "and not" clause in the case, or a when
-clause.
when
-clause to exclude the value 999. The logic is the same in both switch
expressions.int z = 999; // Version 1: use "and not" to handle an excepted value. string result = z switch { (> 10) and not 999 => "A", _ => "B", }; Console.WriteLine(result); // Version 2: use when to handle the excepted value. string result2 = z switch { (> 10) when z != 999 => "A", _ => "B", }; Console.WriteLine(result2);B B
With "when" in a case statement, we can place another condition that must evaluate to true before a block of code is executed. This makes switch
statements more like if
-statements.