Pattern Matching in C# for Beginners
Tags: csharp, dotnet, productivity
Published: 2021-10-27 11:58:54

---
title: Pattern Matching in C# for Beginners
published: true
date: 2021-10-27 10:00:32 UTC
tags: csharp, dotnet, productivity
canonical_url: https://www.syncfusion.com/blogs/post/pattern-matching-in-c-for-beginners.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hvo7xox7ce09yf2m9z7z.png
---

Pattern matching in [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language) "Link to Wikipedia page for C Sharp language") helps developers handle control flows with variables and types that are not linked by a hierarchy of inheritance. Pattern matching was implemented in C# 7.0 to add power to the existing language operators and statements. Since then, pattern matching capabilities have been expanded in every major C# version.

You can perform pattern matching on any type of data, including your own, although primitives still need to align with **if** / **else**. Also, pattern matching will extract expression values.

In this blog, we will briefly discuss some of the pattern matching features.

## The is type pattern expression

The **is** type expression tests the compatibility of an object with a given type.**is** type pattern matching in C# enables the use of type in a control flow, and the logic used is type-driven versus literal value.

Consider the following code example. The code defines three classes: Mathematics, Science, and English.

```csharp
public class Mathematics
{
    public double Score { get; set; }	
    public string GetSubjectDetails() => "Mathematics class";
}
public class Science
{
    public double Score { get; set; }	
    public string GetSubjectDetails() => "Science class";
}
public class English
{ 
    public double Score { get; set; }	
    public string GetSubjectDetails() => "English class";
}
```

You can now code against a subject type using the **is** type. The following code snippet provides an example.

```csharp
public static string GetSubjectDetails (object subject)
{
    if (subject is English e)
         return e.GetSubjectDetails ();    

    if (subject is Science s)
         return s.GetSubjectDetails ();

   if (subject is Mathematics m)
         return m.GetSubjectDetails ();

   throw new ArgumentException("unsupported subject type", nameof(subject));
}
```

The **is** expression checks the variable and assigns it to a new type of variable that is suitable. The**is** type expression works with both the value and the type of reference.

## Switch statements

Instead of a fixed value, the **switch** case statement pattern improves case blocks by allowing us to compare the switch value with different values returned by an expression.

We can do this with a **when** / **case** expression to check a value and perform some action based on the condition check.

```csharp
public static string GetSubjectScore(object subject)
{
     switch (subject)
     {
          case Mathematics m when m.Score >= 90:
                   //Go to the grade calculation.
          case Science s:
                   //Get the subject details.
          case var sub when (sub.Equals(100)):
                    //Got the centum. 
          case null:
                   //Code logic go here.
          default:
               throw new ArgumentException("Unsupported subject type", nameof(subject));
    }
}
```

You can see case statements for null, default, type check, conditions, and the use of conditions without type check ( **case var** ) in the example above. Because **case var** can also match **null** , we put it below **case null** to prevent that from occurring.

Only constants were allowed by the classic **switch** argument. In pattern matching, the order of pattern cases matters due to the dynamic conditions.

Switch expressions were added in C# 8.0. A switch expression is a short approach to return a particular result based on another value. We don’t require the case keywords in switch expressions. The arrow ( **=>** ) takes the place of the colon ( **:** ). The **\_** (underscore) replaces the keyword **default**.

The following code snippet calculates a subject score by using **switch** expressions.

```csharp
var (score1, score2, option) = (50, 40, “+”);
var score = option switch
{
	“+” => score1 + score2,
	“-” => score1 - score2,
	_ => 0
};
Console.WriteLine("Score Details: " + score);
```

## Relational and logical patterns

The **C# 9** version provides support to relational and logical patterns.

They allow the use of relational operators **<** , **>**, **<=**, and **>=**. Use the **to** keyword to express a range in relational patterns.

Logic operators such as **and**, **or**, and **not** can be used.

Using relational and logical patterns, the following code displays the subject grade.

```csharp
var subjectScore = 90;
var grade = subjectScore switch
{
	100 => “Grade O”,
	>= 90 and <= 99 => “Grade A”,
	75 to 89 => “Grade B”,
	> 60 => “Grade C”
};
Console.WriteLine("Subject Grade: " + grade);
```

## Conclusion

We have looked at C#’s support for pattern matching in this blog post. Pattern matching works with any data type. It provides a more concise syntax for testing expressions and taking action when an expression matches. Try out these pattern matching concepts in C# and enhance your productivity!

Syncfusion has over 1,600 components and frameworks for [.NET MAUI(Preview)](https://www.syncfusion.com/maui-controls "Link to .NET MAUI UI controls"), [WinForms](https://www.syncfusion.com/winforms-ui-controls "Link to WinForms UI Controls"), [WPF](https://www.syncfusion.com/wpf-ui-controls "Link to WPF UI Controls"), [WinUI](https://www.syncfusion.com/winui-controls "Link to WinUI Controls"), ASP.NET ([Web Forms](https://www.syncfusion.com/jquery/aspnet-web-forms-ui-controls "Link to ASP.NET Web Forms UI Controls"), [MVC](https://www.syncfusion.com/aspnet-mvc-ui-controls "Link to ASP.NET MVC UI Controls"), [Core](https://www.syncfusion.com/aspnet-core-ui-controls "Link to ASP.NET Core UI Controls")), [UWP](https://www.syncfusion.com/uwp-ui-controls "Link to UWP UI Controls"), [Xamarin](https://www.syncfusion.com/xamarin-ui-controls/ "Link to Xamarin UI Controls"), [Flutter](https://www.syncfusion.com/flutter-widgets "Link to Flutter UI Controls"), [JavaScript](https://www.syncfusion.com/javascript-ui-controls "Link to JavaScript UI Controls"), [Angular](https://www.syncfusion.com/angular-ui-components "Link to Angular UI Controls"), [Blazor](https://www.syncfusion.com/blazor-components "Link to Blazor UI Controls"), [Vue](https://www.syncfusion.com/vue-ui-components "Link to Vue UI Controls"), and [React](https://www.syncfusion.com/react-ui-components "Link to React UI Controls"). Use them to boost your application development speed.

If you have any concerns or need any clarification, please mention them in the comments section below. You can also reach us through our [support forums](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/ "Link to Syncfusion Feedback Portal").

## Related blogs

- [Add, Remove, Extract, and Replace Images in PDF using C#](https://dev.to/syncfusion/add-remove-extract-and-replace-images-in-pdf-using-c-480i "Link to Add, Remove, Extract, and Replace Images in PDF using C# blog")
- [4 Features Every Developer Must Know in C# 9.0](https://dev.to/karthickramasamy08/4-features-every-developer-must-know-in-c-9-0-5bpe-temp-slug-9388860 "Link to 4 Features Every Developer Must Know in C# 9.0 blog")
- [Understanding C# Anonymous Types](https://dev.to/karthickramasamy08/understanding-c-anonymous-types-2c66-temp-slug-4931589 "Link to Understanding C# Anonymous Types blog")
- [Create ZUGFeRD-Compliant PDF Invoice in C#](https://www.syncfusion.com/blogs/post/create-zugferd-compliant-pdf-invoices-in-c.aspx "Link to Create ZUGFeRD-Compliant PDF Invoice in C# blog")