What is the purpose of the parenthesis in this switch and case label?
It is a capability of pattern matching that was introduced in C# 8
. { }
matches any non-null value. n
is used to declare a variable that will hold matched value. Here is a sample from MSDN that shows usage of { }
.
Explanation of your sample:
switch (itemsList.Count())
{
case 0:
throw new Exception("No items with that model");
case 1:
return itemsList;
// If itemsList.Count() != 0 && itemsList.Count() != 1 then it will
// be checked against this case statement.
// Because itemsList.Count() is a non-null value, then its value will
// be assigned to n and then a condition agaist n will be checked.
// If condition aginst n returns true, then this case statement is
// considered satisfied and its body will be executed.
case { } n when n > 1:
return itemsList;
}
It is known as property pattern
. The {}
deals with remaining nonnull objects. Property patterns express a property that needs to have a specific constant value. But, in your example, I think it is just to use n
in the switch-expression by assuring n
is not null. I mean its equivalent is as follows.
if (itemsList is {} n && n.Count() > 1)
{
return itemsList;
}