Pattern Matching In C#

Patterns are introduced in 7.0 to bring power to some existing language operators and statements. Currently, pattern matching is partially implemented in C# 7.0 and more work is expected to be done in the next versions of the language. As described in the referenced document, the pattern matching feature introduced in C# 7.0 has the following two advantages.

  • You can perform pattern matching on any data type, even your own, whereas with if/else, you always need primitives to match.
  • Pattern matching can extract values from your expression.
  • C# 7.0 introduces pattern matching in two cases, the is expression and the switch statement.

Is expressions

The expression checks if an object is compatible with a given type. The code listed in Listing 1 defines three classes, Person, Author, and Reader. Both the Author and Reader classes are inherited from the Person class.

// Person class
class Person {
    private string name;
    private Int16 age;
    private string sex;
    public string Name {
        get {
            return this.name;
        }
        set {
            this.name = value;
        }
    }
    public Int16 Age {
        get {
            return this.age;
        }
        set {
            this.age = value;
        }
    }
    public string Sex {
        get {
            return this.sex;
        }
        set {
            this.sex = value;
        }
    }
}

// Author class
class Author: Person {
    private string book_title;
    private Int16 pub_year;
    public string Title {
        get {
            return this.book_title;
        }
        set {
            this.book_title = value;
        }
    }
    public Int16 Year {
        get {
            return this.pub_year;
        }
        set {
            this.pub_year = value;
        }
    }
    public Author(string name, Int16 age, string sex, string book, Int16 year) {
        this.Name = name;
        this.Age = age;
        this.Sex = sex;
        this.book_title = book;
        this.pub_year = year;
    }
}

// Reader class
class Reader: Person {
    private string interest;
    private string job;
    public Reader(string name, Int16 age, string sex, string interest, string job) {
        this.Name = name;
        this.Age = age;
        this.Sex = sex;
        this.interest = interest;
        this.job = job;
    }
}

Listing 1

Now, let’s take a look at the code snippet in Listing 2, where we create three objects of types Person, Author, and Reader. Later, the code uses the is expression to see if these objects are compatible with the types or not.

Person p = new Person();
Author a = new Author("Mahesh Chand", 33, "male", "ADO.NET Programming", 2003);
Reader r = new Reader("Ryan", 21, "male", "reading", "developer");
if (a is Person)
    Console.WriteLine("Author is a Person");
else
    Console.WriteLine("Author is not a person");
if (a is Reader)
    Console.WriteLine("Author is a Reader");
else
    Console.WriteLine("Author is not a Reader");

Listing 2

Is expressions pattern

C# 7.0 extends the expression by adding a pattern on the right side of the expression, which can be a value extracted from an expression. In C# 7.0, the following statement is correct.

if (a is Person p1)

Listing 3

In Listing 3, the right side of the is can be a value returned by an expression.

Switch statement pattern

The Switch case statement pattern enhances the case blocks by allowing us to compare the value of the switch with the value returned by an expression, rather than a fixed value. The code snippet in Listing 4 compares an expression value.

switch (r) {
    case Person person1 when (person1.Age == 33):
        Console.WriteLine($"Person {person1.Name}");
        break;
    case Reader reader1 when (reader1.Age == 21):
        Console.WriteLine($"Reader {reader1.Name}");
        break;
    default:
        Console.WriteLine("Not found");
        break;
}

Listing 4

In the above code snippet in Listing 4, r is both Person and Reader, but the Age is 21. Thus, the second case is matched.

Summary

C# 7.0 introduced a new feature, pattern matching. In this article, we learned about two patterns and how to use them in our code.

Next C# 7.0 Feature: Deconstruction in C# 7.0

References

References used to write this article.

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.