The C# switch statement and parentheses

92 views Asked by At

Which example is correct in terms of number of parentheses? The C# 12 compiler accepts both.

EXAMPLE 1:

switch ((value, Frozen))
{
    case ( >= 0 and <= 9, false):
        break;
    case (_, false):
        break;
    case (_, true):
        break;
}

EXAMPLE 2:

switch (value, Frozen)
{
    case ( >= 0 and <= 9, false):
        break;
    case (_, false):
        break;
    case (_, true):
        break;
}
2

There are 2 answers

0
Marc Gravell On

There is no difference, so both are correct; but usually redundant (unnecessary) parentheses should be omitted unless they help clarity (especially in complex mathematical expressions, where explicit usage of parentheses are preferable to having to reliably know the operator precedence rules). Parentheses in this context can mean:

  1. a sub-expression to be evaluated
  2. the boundary of a value-tuple

but: the presence of multiple comma-delimited terms is what distinguishes between these; a value-tuple usage must have at least 2 terms, precisely to avoid this confusion.

So:

  • the outer parentheses are simply denoting a sub-expression (you can have any number of these, but they serve no purpose)
  • the innermost parentheses denote the value-tuple, because of the comma
2
Grace p s On

In my point of view, second block is correct even though both are correct and gives the same output. In C#, switching statements are typically used with a single expression, and pattern matching is utilized in case statements. Your examples seem to use a tuple as the switch expression, which is not standard syntax in C#.

To use pattern matching, it's best to use a single expression and apply patterns to the case statements.