Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (152).NET Core  (26)Angular  (49)ASP.NET  (48)ASP.NET Core  (64)ASP.NET MVC  (86)Azure  (29)Blazor  (107)DocIO  (20)Essential JS 2  (72)Essential Studio  (164)File Formats  (20)Flutter  (115)JavaScript  (150)Microsoft  (102)PDF  (59)React  (33)Succinctly series  (124)Syncfusion  (490)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (26)Webinar  (27)Windows Forms  (55)WinUI  (27)WPF  (123)Xamarin  (132)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (108)Chart  (53)Cloud  (10)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (50)Development  (263)Doc  (7)DockingManager  (1)eBook  (94)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (20)Extensions  (15)File Manager  (4)Gantt  (9)Gauge  (7)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (233)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (25)Performance  (7)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (29)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (10)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (65)UI  (139)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (19)Visual Studio Code  (13)Web  (227)What's new  (146)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top