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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With