Pattern Matching in C# for Beginners | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)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  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)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.
          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.

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

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

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed