Pattern Matching - C# Tutorial
C# Course / Version Features / Pattern Matching

Pattern Matching

BLUF: Mastering Pattern Matching is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Pattern Matching

C# is a powerful, modern language for enterprise solutions. Discover how Pattern Matching enhances your development workflow in the guide below.

C# pattern matching is a functionality enabling us to conduct matching on data or objects. Pattern matching can be executed using the is operator and switch statement.

The is keyword is utilized to verify if an object is compatible with a specified type or not.

In this instance, we are executing the is expression.

C# Pattern Matching using is Example

Example

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; set; } = "Rahul kumar";
    }
    class PatternMatchingExample
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            if(student is Student)
            {
                Console.WriteLine(student.Name);
            }
        }
    }
}

Output:

Output

Rahul kumar

We can also implement pattern matching in a switch statement. Take a look at the following illustration.

C# Pattern in Switch Case Example 2

Example

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; set; } = "Rahul kumar";
    }
    class Teacher
    {
        public string Name { get; set; } = "Peter";
        public string Specialization { get; set; } = "Computer Science";
    }
    class PatternMatchingExample
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Teacher teacher = new Teacher();
            PatterInSwitch(student);
            PatterInSwitch(teacher);
        }
        public static void PatterInSwitch(object obj)
        {
            switch (obj)
            {
                case Student student:
                    Console.WriteLine(student.Name);
                    break;
                case Teacher teacher:
                    Console.WriteLine(teacher.Name);
                    Console.WriteLine(teacher.Specialization);
                    break;
                default:
                    throw new ArgumentException(
                        message: "Oject is not recognized",
                        paramName: nameof(obj));
            }
        }
    }
}

Output:

Output

Rahul kumar
Peter
Computer Science

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience