Let us explore Pattern Matching of C# 7.0 inside Visual Studio "15" Preview 2

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 1278 red flag

In this article, we will explore the Pattern Matching of C# 7.0


 Download source code for Let us explore Pattern Matching of C# 7.0 inside Visual Studio "15" Preview 2

Recommendation
Read A Beginners Guide to work with ASP.NET Web API and AngularJS before this article.

Introduction

Microsoft has announced its Visual Studio Enterprise "15" Preview 2. We have download the same from here. In the earlier article, we have explore Local Function feature of C# 7.0. In this article, we will explore the Pattern Matching of C# 7.0

What is Pattern Matching?

Patterns are used in the is operator and in a switch-statement to express the shape of data against which incoming data is to be compared. Patterns may be recursive so that sub parts of the data may be matched against sub patterns.

Using the code

Case 1: Type Pattern using the IS operator

The Type Pattern performs a run time check for the data types. Let's understand it's usage with a simple example.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {            
            void TypePatternExample(object data)
            {
                var result = data is Tuple<int, int> ? "It is tuple" : "Sorry!!! Data Type pattern does not match ";
                Console. WriteLine(result);               
            }

            Tuple<int, int> t = Tuple.Create(10, 20);
            TypePatternExample(t); //success
            TypePatternExample(20); //failure
            Console.ReadKey();
        }
    }
}

In the above program, we are checking where the datatype passed is of type Tuple<int, int>. The checking happens at runtime.

The result

Case 2: Switch-Based Pattern

Another kind of pattern can be made using a switch statement. It can also contain guard close. Let's look into the below program

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            #region Switch-Based Pattern

            foreach (object o in new List<object>() { 10, 20, null, "hello", 12.5 })
            {
                switch (o)
                {
                    case string s:
                        Console.WriteLine($"Entered value {o} is a string");
                        break;

                    case int i:
                        Console.WriteLine($"Entered value {o} is an integer");

                        switch(i)
                        {
                            case int j 
                                 when j == 10:
                                    Console.WriteLine($"Entered value {j} is equal to 10");
                                     break;
                            case int j
                                 when j > 10:
                                Console.WriteLine($"Entered value {j} is more than 10");
                                break;
                        }
                       
                        break;

                    case null:
                        Console.WriteLine($"Entered value {o} is a null");
                        break;

                    default:
                        Console.WriteLine($"Entered value {o} does not find any matching pattern");
                        break;
                }
            }
            #endregion
            Console.ReadKey();
        } 
    }
}

The program takes a collection of objects, loops through that and then performs a type pattern matching. Also, if the data type is an integer, it checks the boundary values specified.

The result

Case 3: Wild Card Pattern Matching

Every expression match the wildcard pattern.

    foreach (object o in new List<object>() { 10, 20, null, "hello", 12.5 })
    {
        if (o is *)
        {
            Console.WriteLine("It's a match for {0}",o);
        }

        if (o is string)
        {
            Console.WriteLine("Match data is {0}", o);
        }
    }

It's obvious from the program that, * is the wild card that matches all the types while the second if block matches only the string type.

Reference

Pattern Matching for C#

Conclusion

It's a nice feature available in C# 7.0 in Visual Studio Enterprise "15" Preview 2. Hope we all have enjoyed the article.Thanks for reading. Zipped file attached.

Recommendation
Read Let's know about ComputerInfo Class after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)