DEV Community

Discussion on: Pattern Matching Examples in C#

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.