Skip to content

C# Pattern Matching

C# Pattern Matching

C# Pattern matching features allow developers to write more expressive and concise code when working with complex data structures. With the release of C# 11.0, this feature has been expanded to include new patterns and enhancements to existing ones. In this article, we will explore the different types of pattern matching and provide real-world code examples to illustrate their usage.

There are several types of pattern matching in C#, including:

  • Type patterns
  • Property patterns
  • Tuple patterns
  • Switch expressions

 

Type Patterns

This is the most basic type of pattern matching in C#, and is used to check if a value is of a specific type. Type patterns are used to match an object against a specific type. They can also be used to check if an object is null or if it is an instance of a specific class or interface. For example:

In this example, the method: PrintLength takes an object as a parameter and uses type patterns to check if it is a string or a collection. If it is a string, it prints the length of the string. If it is a collection, it prints the number of items in the collection.

In C# 11.0, we can now use the or operator to match against multiple types. For example:

 

In the above code, the PrintType method takes an object as a parameter and checks if it is a string or an int. If the object matches either of these types, the method prints the name of the type.

 

 

Property Patterns

Property patterns are used to match an object against a property values of an object. This is useful when you need to match on a specific value of a property, rather than just the type of the object. For example:

 

In this example, the method GreetPerson takes a Person object as a parameter and uses property patterns to match on the person’s name and age. If the person’s name is Alice and her age is 25, it prints Hello, Alice!. If the person’s name is Bob and his age is 30, it prints Hello, Bob!. If the person does not match either of these patterns, it prints Hello, stranger!.

 

C# 11.0 introduces the ability to match against multiple properties using the “and” operator. For example:

 

In the above code, the PrintPersonInfo method takes an object of type Person and checks if the object has a Name property that is a string and an Age property that is between 18 and 65. If the object matches these criteria, the method prints the person’s name and age.

 

Tuple Patterns

Tuple patterns are used to match on the the elements of a tuple. This is useful when you need to match on multiple values at once. For example:

 

In this example, the method PrintTuple takes a tuple of two integers as a parameter and uses tuple patterns to match on the values of the tuple.

  • If both values are 0, it prints The tuple is (0, 0).
  • If the second value is 0, it prints The tuple is ({x}, 0). where x is the value of the first element.
  • If the first value is 0, it prints The tuple is (0, {y}). where y is the value of the second element. If both values are non-zero, it prints The tuple is ({x}, {y})..

 

C# 11.0 introduces the ability to use discard (_) to ignore specific elements of the tuple. For example:

 

In the above code, the PrintTuple method takes a tuple with an int and a string as elements. The method checks if the tuple’s second element (the string) has a length of 5 or more characters. The first element of the tuple is ignored using the discard (_) operator. If you want to skyrocket your C# career, check out our powerful ASP.NET full-stack web development course that also covers test-driven development.

Switch Expressions

Switch expressions are used to match a value against multiple patterns. Switch expressions are a more concise way to write switch statements, and can be used with any type of pattern matching. They are useful when you need to return a value based on the matched pattern. For example:

 

In this example, the method GetMessage takes an object as a parameter and uses switch expressions to match on different patterns.

  • If the object is null, it returns The object is null..
  • If the object is a string, it returns The string is '{str}'..
  • If the object is a positive integer, it returns The number is positive ({num})..
  • If the object is a negative integer, it returns The number is negative ({num})..
  • If the object does not match any of these patterns, it returns I can't detect the object's type..

In C# 11.0, we can now use the “or” operator to match against multiple patterns in a single case statement. For example:

In the above code, the GetGrade method takes a score as a parameter and returns the corresponding grade based on the score. The method uses multiple patterns in the switch expression to match the score against different ranges of values.

C# Pattern Matching Conclusion

Pattern matching allows developers to write more expressive and concise code. There are several types of pattern matching in C#, including type patterns, property patterns, tuple patterns, and switch expressions. There’s also another one you can use to simplify exception handling. You can learn more about it in my exception handling article. By understanding how to use these different types of pattern matching, you can write more expressive and maintainable code.C# 11.0 introduces new patterns and enhancements to existing ones, making pattern matching even more useful. By using pattern matching, developers can write code that is easier to read and maintain, leading to more efficient and bug-free applications. The examples we’ve provided in this article are just a few of the many ways pattern matching can be used in C#. By leveraging these patterns, developers can write code that is even more concise and expressive.

Some additional patterns available in C# including the not operator,  which can be used to negate a pattern, Relational patterns, and List patterns. Leave us a reply if you want us to write more about them. With the enhancements in C# 11.0, pattern matching has become even more useful in a variety of real-world scenarios. As a developer, it is important to stay up-to-date with the latest features in the language to write efficient and maintainable code.

Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide