DEV Community

Discussion on: Pattern Matching Examples in C#

Collapse
 
uchitesting profile image
UchiTesting • Edited

Hello.

Thanks for this article. I once found a bit of that syntax with switch and the when keyword. I was badly wishing there is such thing because this is handy but I didn't know it is so complete. I'm going through the codes and playing them in Visual Studio.

I have questions I note as I go so there may be one or more.

Variable Patterns :
There is apparently a small error in the article because the output gives "Hi" alone. Which makes sense to me when I read the code.

_ when greetWithName == false => $"Hi", applies.

Format a string
Modified the code so that phone is null.
Does not seem to work as expected and goes to the 1st pattern.
Any Idea why?

Regards.

Collapse
 
timdeschryver profile image
Tim Deschryver

Thanks! I think you found some syntax mistakes in the snippets, and again thanks for pointing them out.

Variable pattern should be:

var greetWithName = true;
var output = "Mrs. Kim" switch
{
    _ when greetWithName == false => $"Hi",
    "Tim" => "Hi Tim!",
    var str when str.StartsWith("Mrs.") || str.StartsWith("Mr.") => $"Greetings {str}",
    var str => $"Hello ${str}",
};
// output: Greetings Mrs. Kim
Enter fullscreen mode Exit fullscreen mode

Format a string should use and instead of or:

var output = contactInfo switch
{
    { TelephoneNumber: not null } and { TelephoneNumber: not "" } => $"{contactInfo.FirstName} {contactInfo.LastName} ({contactInfo.TelephoneNumber})",
    _ => $"{contactInfo.FirstName} {contactInfo.LastName}"
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
uchitesting profile image
UchiTesting

Thanks for the fixes.
Tried them and they work.
I must admit that when reading the code this or looked legit.
But when you go back to boolean it makes sense.

TelephoneNumber is null
TelephoneNumber not null → False → 0
TelephoneNumber not "" → True → 1

0 or 1 is 1 so it executes the line.
0 and 1 is 0 so it filters accordingly.

Regards.