Home
C#
when Keyword (switch when)
This page was last reviewed on Sep 19, 2024.
Dot Net Perls
When. 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.
switch
case
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.
Example. 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
Result Because the count is 20 and the valid 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
Excepted value. 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.
Version 1 We match values greater than 10 except not 999 (by using the "and not" keywords).
Version 2 We use a when-clause to exclude the value 999. The logic is the same in both switch expressions.
Info It is probably more elegant to use "and not" in this situation, as we do not need to reference the variable name a second time.
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 19, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.