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
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:
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
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:
Rahul kumar
Peter
Computer Science