Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the parenthesis in this switch and case label?

Tags:

c#

c#-8.0

I am writing a function for an item service where if the user requests for all items under a certain name it will return them all. Such as all the phones that are iPhone X's etc.

I got help to make one of the functions work where if there are more than 1 items it will return them all (this is the third case):

var itemsList = items.ToList();

switch (itemsList.Count())
{
    case 0:
        throw new Exception("No items with that model");

    case 1:
        return itemsList;

    case { } n when n > 1:
        return itemsList;
}

return null;

What confuses me is what are the { } for? I was told it was "a holding place as sub for stating the type" I am unsure of what they mean by this.

How does it work too? I am not sure what n is for.

Any help is greatly appreciated!

PROGRESS: After following up with the helper, I now know that { } is similar to var. But I am still unsure why it is only used here.

like image 839
Suraj Cheema Avatar asked May 01 '20 11:05

Suraj Cheema


1 Answers

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;
}
like image 138
Iliar Turdushev Avatar answered Oct 10 '22 03:10

Iliar Turdushev