Working With Pattern Matching In C# 7.0

I am here to continue the series related to C# 7.0 features. Today we will be going through another feature called pattern matching and will demonstrate its uses in an easy manner.

Pattern matching

Pattern matching is introduced in C# 7.0 to bring more logical ability in the language. Patterns are not new in the programming languages however it’s introduced first time in C# with the limited features and more is expected to come in the upcoming versions.

Pattern matching is useful in many ways however the cases are given below, which C# 7.0 currently supports.

  • Pattern matching can be used with any data type including custom whereas if/else can only be used with primitive types.
  • Pattern matching has the ability to extract the data from the expression.

C# 7.0 introduced two type of pattern matching, as shown below.

  • With “is” expression
  • With switch..case statement

Let’s go through on these patterns in detail.

Pattern with “is” expression:

To support pattern matching, a new construct has been introduced in the right side of the type in the “is” expression. The code snippet given below illustrates the same.

  1. //C# 7.0 extends the is expression by adding a pattern in the right side of the expression,   
  2.             //that can be a value extracted from an expression  
  3.             var myData = "My Custom Data";  
  4.             var myData2 = myData is string ? "String" : "Not a string";  
  5.             var myData3 = myData is string p ? p : "Not a String";  
  6.             Console.WriteLine(myData2);  
  7.             Console.WriteLine(myData3);  

Look at the tiny variable “p” after string type. Have you seen it earlier?

This is something, which is  introduced in C# 7.0 to support pattern matching. Also just to add, I just took name “p” however it can be any permitted variable name.

Output

C#

As you can see the second print statement has printed the value of “p” as “My Custom Data” as pattern matching and variable “p” was listening to the value of the variable myData, which is left to the “is” operator.

The screenshot given below explains the same.

C#

Pattern with switch..case statement

Pattern matching with switch..case statement is yet another newly introduced feature.

Now, switch..case statement can work with the expressions as well.

Let’s look at example to see this in action.

  1. public static void TestSwitchPattern()  
  2.         {  
  3.             var emp = new Employee();  
  4.             var dev = new Developer() { EmpId = 101, Name = "Prakash", City = "Satna" };  
  5.             var man = new Manager() { EmpId = 102, Name = "Srinivas", City = "Hyderabad" };  
  6.   
  7.             switch (man)  
  8.             {  
  9.                 case Employee e when (e.EmpId == 101):  
  10.                     Console.WriteLine($"Employee Name: {e.Name}");  
  11.                     break;  
  12.                 case Manager m when (m.EmpId == 102):  
  13.                     Console.WriteLine($"Employee Name: {m.Name}");  
  14.                     break;  
  15.                 default:  
  16.                     Console.WriteLine("Not found");  
  17.                     break;  
  18.             }  
  19.         }  
  20.   
  21.         class Employee  
  22.         {  
  23.             public int EmpId { get; set; }  
  24.             public string Name { get; set; }  
  25.             public string City { get; set; }  
  26.         }  
  27.         class Developer : Employee  
  28.         {}  
  29.         class Manager : Employee  
  30.         {}  

Output

C#

Did you figure out why and how the above output generated?

If not, then here’s an explanation,

In switch, we passed manager object (man), so it went to matching manager case and evaluated the expression and since it’s passed due to matching EmpId found, it printed the employee name.

Now as an experiment, if you change EmpId as suppose 105 in the statement given below.

  1. var man = new Manager() { EmpId = 105, Name = "Srinivas", City = "Hyderabad" };  

The output is given below.

C#

Since the expression evaluated as false in the matching case, it went to default and printed Not found.

Conclusion

In this article, first we have gone through what pattern matching stands for followed by explaining the related features introduced in C# 7.0. Later we explained both types of pattern matching constructs with the examples.

You can also download the attached demo project (PatternMatch.zip) by going through the full source code referred in the article.

Hope, you have liked the article. Look forward for your comments/suggestions.

In case you also want to go through the previous parts of the series, the links are given below.

Up Next
    Ebook Download
    View all
    Learn
    View all