C# 9 pattern matching

C# 9 pattern matching

The previous article in our C# 9 series looked at top-level programs and target-typed expressions. In this article, we’ll cover new features for pattern matching. You can find an overview of the syntax offered by previous versions of C# in C# 8 pattern matching.

Type patterns

When checking against a type, previous versions of C# required you to include a variable name (or a _ discard). This is no longer required with C# 9:

// is pattern with Type
if (input is Person)
...
 
// case pattern with Type
switch (input)
{
  case Person:
    ...  
 
// is pattern with tuple Type
if (input is (int, string))
...

Combining patterns

With the is expression in earlier versions of C#, you could already combine patterns using regular logical operators:

if (person is Student || person is Teacher)
...

However, this doesn’t work for switch expressions and switch case labels. C# 9 adds support for combining patterns using the and and or keywords, which works for both if and switch:

if (person is Student or Teacher)
...
 
decimal discount = person switch
{
   Student or Teacher => 0.1m,
   _ => 0
};
 
switch (person)
{
   case Student or Teacher:
      ...

The and patterns have higher precedence than the or patterns. You can add parentheses to change or clarify the precedence.

Inverting patterns

With C# 9, you can invert patterns using the not keyword:

if (person is not Student)
...

switch (person)
{
  case not Student:
    ...

An interesting case is the is not null pattern. This will check whether the reference is not null. Using != null may check something different when the type overloads the != operator.

if (person is not null)
...

Relational patterns

Relational patterns allow you to compare an expression to a constant numeric value:

decimal discount = age switch
{
   <= 2 => 1,
   < 6  => 0.5m,
   < 10 => 0.2m,
   _    => 0
};

Patterns within patterns

Patterns can also contain other patterns. This nesting lets you express complex conditions in a concise and readable way. The following example combines several types of patterns:

if (person is Student { Age : >20 and <30 })
...

Conclusion

In this article, we looked at the new pattern matching features in C# 9. The additions allow you to express more complex conditions with a clear, concise syntax.

C# 9 can be used with the .NET 5 SDK, which is available on
Red Hat Enterprise Linux and Red Hat OpenShift, on Fedora, and from Microsoft for Windows, macOS, and other Linux distributions.

Share