Pattern Matching in C# for Beginners | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (182).NET Core  (28).NET MAUI  (231)Angular  (117)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (42)Black Friday Deal  (1)Blazor  (242)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (201)File Formats  (74)Flutter  (138)JavaScript  (227)Microsoft  (122)PDF  (84)Python  (1)React  (107)Streamlit  (1)Succinctly series  (131)Syncfusion  (985)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (164)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (11)Business intelligence  (55)Button  (4)C#  (164)Chart  (152)Chart of the week  (61)Cloud  (16)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (74)Development  (692)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (31)File Manager  (8)Gantt  (22)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (526)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (46)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (420)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (643)What's new  (353)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Pattern Matching in C# for Beginners

Pattern Matching in C# for Beginners

Pattern matching in C# 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.

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.

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.

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.
               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.

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.

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);


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)WinFormsWPFWinUI, ASP.NET (Web FormsMVCCore), UWPXamarinFlutterJavaScriptAngularBlazorVue, and React. 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 forumsDirect-Trac, or feedback portal.

Related blogs


Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed