Pattern Matching In C#

|  Posted: December 21, 2020  |  Categories: .NET C# Microsoft

Pattern matching is one of the coolest things that was introduced in C# 7.0. It evolved in a smarter way and in C# 9.0 it became more powerful. We already write pattern matching expressions using if and switch statements where we are extracting some values by matching some patterns.

In this blog, we will explore some interesting operators/ clauses which can be used to write pattern matching expressions more effectively.

is Expression

The is operator checks if the type of the given variables is the same. In C#, it works with both value types as well as reference types. In the below example, we have compared whether the created object belongs to the Student class.

If you want to check whether the respective object is null or not null, you can also do it with the is Expression.

In some scenarios, you will have a separate function like below to check if the given object is a Student object.

In the above example, before C# 7.0 you need to typecast the respective object and you can do the respective operations. But now you can simplify the code using extensions to the is expression by assigning a variable to it. Here we are trying to avoid typecasting and also improving the readability of the code.

Switch Pattern Matching

If you want to compare one or two conditions, if and if..else statements should be enough. But if you want to compare more conditions, you should definitely fall back to switch statements.

The traditional switch statement was just a pattern expression that supports comparing constants, string, and number. But now you can also use the switch statement to compare types.

In the above code, it will try to find out the type of the object, or else it will fallback to the default case. It will be evaluated at the last irrespective of its textual order.

Defining a default case is totally optional. If you don’t define a default case and if the object does not match any cases, it’ll continue to execute the next line of code.

using when clause in case expression

Sometimes, we might face a situation of using an if condition inside the switch cases. These can be avoided using the when clause in switch expression. Let’s take the previous example,

You can apply multiple case labels to one switch section. In the above example, there are two cases with when clauses. If any one of the conditions is true, it will return the “First Name Suhas” string. 

And also in the above example, there are two variables introduced in the first switch section, student and employee. If you notice, we haven’t used it in the switch block. If either of the cases matched, there will be a variable assigned to it.

But unfortunately, it will be impossible to find which has been assigned at compile time. So it’s not a good practice, to introduce a new variable in the case statement when you have multiple cases. But like in the above example, you can use it in the when clause.

null and not null

You can also use null and not null cases if you want to check whether the object is null or not null.

In the above example, first, it will try to find out whether the given object is of Employee, Student, or Teacher type. And then it will check for the null and not null condition. If none of the cases match, it will fall back to the default section.

var declaration in case expression

You can introduce var in your switch case expressions. In doing so, there are rules introduced to the pattern match.

  • var declaration follows normal type inference rules. The type is inferred to the static type in the switch case expression
  • var declaration does not have a null check. So it may be null and you have a check for the null condition when you use var in case expression
  • var case can also be useful when you want to check the null or not null condition

In the above example, you can see by using var we are checking the null, not null, whitespace validation condition. In this type of scenarios, var will be very much useful

Conclusion

Pattern Matching works with any data type. Basically, you will write expressions to make a control flow decision based upon the given conditions. The process of pattern matching is evolving from C# 7.0. My favorite one, is Expression and when clause. It gives you more flexibility in evaluating the respective conditions.

So to give a summary on this blog

  • is Expression can be used to compare the types.
  • is Expression can also be used to check whether the object is null or not null.
  • If there are more conditions to evaluate you can fallback to switch.
  • You can also use the switch statement to compare types.
  • Using when clause in case section helps you to evaluate the conditions effectively.
  • You can also use var in cases which helps you to evaluate multiple conditions

Thanks for reading this blog. If you have any comments/suggestion just mention it in the comments section. You can check out my other blogs at this link.

Happy Coding! Cheers!

Author: Suhas Parameshwara

Suhas Parameshwara is a Full Stack Web Application Developer working with Kovai.Co. He acquired a Bachelor's Degree in Computer Science from Sri Eshwar College of Engineering, Tamil Nadu (Coimbatore). He has around 3+ years of experience in Microsoft Technologies such as C#, ASP.NET, .NET Core, SQL, Azure, Visual Studio, Visual Studio Code, and UI technologies such as HTML, CSS, JS, and Angular. He is also a Blogger and a Speaker and tries to grab all the opportunities to stay connected with the technical community. For his continuous contribution to the community, he has been recognized as Microsoft MVP for Developer Technologies Category from 2020.

Get notified about any future events

Interested in learning more about TechMeet360 or knowing about any future events? Sign up below to get notified.

Back to Top