Introduction
C# pattern matching is a feature that allows us to perform matching on data or any object. We can perform pattern matching using the Is expression and Switch statement. Is expression is used to check, whether an object is compatible with the given type or not? A switch statement has been enhanced with the const pattern, the type pattern, and the var pattern.
“is” Operator with Pattern Matching
The “is” operator is available since the first version of C#. This operator can be used to check if an object is compatible with a specific type. With the C# 7.0 extensions, the “is” operator can be used to check for patterns.
Const Pattern
One available pattern in C# 7.0 is the const pattern. The below example will explain the const pattern.
- //Constant Patterns
- if (o is null) Console.WriteLine($ "Object is null");
- if (o.ValConstant is 32) Console.WriteLine($” o.ValConstant is 32 ");
Type Pattern
With this pattern, you can verify if the object is compatible with the specific type.
- //Type Patterns
- if (o.ValConstant is int i) Console.WriteLine($ "its a type pattern with an int and its value = {i}");
- if (o is Associate A) Console.WriteLine($ "its a type pattern with Associate and FirstName ={A.FirstName}");
Var Pattern
This type is using the var keyword. Here the object is always type.
- //Var Pattern
- if (o is
- var aa) Console.WriteLine($ "its a var type type : {aa?.GetType()?.Name}");
- namespace PatternMatching {
- class Program {
- static void Main(string[] args) {
- var records = new List < Associate > {
- new Associate("Prasad", 32, null),
- new Associate("Praveen", 58, null)
- };
- foreach(var obj in records) {
- IsPatternMatching(obj);
- }
- }
- private static void IsPatternMatching(Associate o) {
- //Constant Patterns
- if (o is null) Console.WriteLine($ "Object is null");
- if (o.ValConstant is 32) Console.WriteLine($ "{o.ValConstant} is constant");
- //Type Patterns
- if (o.ValConstant is int i) Console.WriteLine($ "its a type pattern with an int and its value = {i}");
- if (o is Associate A) Console.WriteLine($ "its a type pattern with Associate and FirstName ={A.FirstName}");
- //Var Pattern
- if (o is
- var aa) Console.WriteLine($ "its a var type type : {aa?.GetType()?.Name}");
- }
- }
- public class Associate {
- public string FirstName {
- get;
- set;
- }
- public int ValConstant {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public Associate(string firstName, int value, string lastName) {
- FirstName = firstName;
- ValConstant = value;
- LastName = lastName;
- }
- }
- }

Join the conversation! Your thoughts help the community grow.