top of page
Writer's pictureThe Tech Platform

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!



Source: Medium - Rajeshwari Pandinagarajan


The Tech Platform

0 comments

Recent Posts

See All

Comments


bottom of page