Introduction
In today’s article we will look at pattern matching in C#. This is a way to match certain members in our objects or the objects themselves to certain conditions and values. This is an especially useful technique to make our code more concise and readable. We will look at several different patterns for matching.
What is Pattern Matching?
In simple terms we can define Pattern Matching as the code we write to test for certain values and conditions. In the past we normally used If and Switch statements for this purpose. Although, these worked perfectly and will also work now, we now also have the choice of more robust code writing options while using these pattern matching techniques. We will look at five patterns in the code below. Different patterns have been introduced with different release versions of C#. However, for this article I will be using C# 9.0, which will have all the patterns discussed in this article.
Creating a solution and looking into Pattern Matching
First let us create a new console application using Visual Studio 2019 Community Edition.



After the project has been created, remember to set the target framework to .NET 5 to use all features up to C# 9.0.

Next, create an Employee class as below,
- namespace ConsoleAppPatternMatchingTests
- {
- class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
- }
- }
And add the below code in the Program.cs file,
- using System;
- using ConsoleAppPatternMatchingTests;
- // Constant Patterns
- var employee = new Employee() { Id = 1, Name = "John Doe", Age = 0 };
- if (employee.Age is 0)
- Console.WriteLine($"{employee.Name} has an age of zero");
- // Null Patterns
- var employeeWithNull = new Employee() { Id = 1, Age = 30 };
- if (employeeWithNull.Name is null)
- Console.WriteLine($"The employee with Id: {employeeWithNull.Id} has a name that is null");
- //Negated Patterns
- var employeeWithoutNull = new Employee() { Id = 1, Name = "John Doe", Age = 30 };
- if (employeeWithoutNull.Name is not null)
- Console.WriteLine($"{employeeWithoutNull.Name} name is not null");
- //Type Patterns
- var employeeType = new Employee() { Id = 1, Name = "John Doe", Age = 30 };
- if (employeeType is Employee emp)
- Console.WriteLine($" Employee name is {emp.Name}");
- //Property Patterns
- var employeeProp = new Employee() { Id = 1, Name = "John Doe", Age = 30 };
- if (employeeProp is { Age: 30 })
- Console.WriteLine($" Employe age is {employeeProp.Age}");
- if (employeeProp is { Age: >25 })
- Console.WriteLine($" Employee age: {employeeProp.Age} is greater than 25");
- Console.ReadKey();


Join the conversation! Your thoughts help the community grow.