ICYMI C# 9 New Features: More Pattern Matching Features

This is part of a series of articles on new features introduced in C# 9.

Pattern matching was introduced in earlier versions of C# and C# 9 continued to evolve this feature. Pattern matching in a more general sense allows you to write an expression and evaluate it to see whether or not it meets some specified characteristic or “pattern”. In some situations pattern matching can reduce the amount of code you need to write and improve readability.

Pattern matching is supported in is expressions, switch statements, and switch expressions.

C# 9 Type Pattern

The type pattern allows your code to perform a runtime check that an expression of a specified type. In C# 9, when using the type pattern you no longer need to assign to a variable or use a discard.

Prior to C# 9:

object o = "hello";
string message = o switch
{
    string _ => "it's a string",
    int _ => "it's an int",
    _ => "it's something else"
};

WriteLine(message);

ReadLine();

Notice in the preceding code the required discards (or variable assignments) _.

From C# 9 this can be simplified to:

object o = "hello";

string message = o switch
{
    string => "it's a string",
    int => "it's an int",
    _ => "it's something else"
};

WriteLine(message);

ReadLine();

Notice that now no discard is required.

Logical, Parenthesized, and Relational Patterns in C# 9

With C# 9 you can now create logical patterns using not, and, or.

Prior to C# 9 you had to write:

if (o != null)
{
    WriteLine(o);
}

From C# 9 you can write:

if (o is not null)
{
    WriteLine(o);
}

As another example, prior to C# 9 you could not write:

if (o is not string)
{
    WriteLine("not a string");
}

Examples of or, and:

string minuteHandDescription = minuteHandValue switch
{
    >=0 and <= 15 => "first quarter",
    >15 and <= 30 => "second quarter",
    >30 and <= 45 => "third quarter",
    (>45 and <=58) or 59 or 60 => "fourth quarter",
    _ => "unknown"
};

Also notice in the preceding code the use of the parenthesized pattern (>45 and <=58) or 59 or 60 to enforce precedence.

The code also makes use of the new C# 9 relational patterns  that include: <, >, <=, and >=.When using these “The right-hand part of a relational pattern must be a constant expression. The constant expression can be of an integer, floating-point, char, or enum type.” [Microsoft]

For more information on patterns check out the C# language reference.

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading