In C# 8.0, property pattern matching is used to determine whether or not the values of the properties of an object are as per the program’s requirement.
Property matching is implemented by comparing property values and model values with the help of switch
expressions.
Although pattern matching was made available in C# 7.0, property pattern matching is only available in C# 8.0 and above.
To check for multiple properties of a single object, the following syntax is used:
static string check(object_type object_name) => object_type switch
{
{prop1: "Y", prop2:"Z" } => "YZ",
_ => "Invalid Input"
};
In the snippet above, prop1
and prop2
are properties of the object named object_name
of type object_type
.
The following program declares a class
named user
with three properties, namely Score
, Name
, and Experience
.
We also define a function that takes as input an instance of the user
class and compares the values of its properties with model values defined in switch expression cases. It returns the corresponding string
if a case label is matched. If no case is matched, the default case is executed.
Using the Controle.WriteLine
function, we output the return value of the function.
using System;public class Program {// declaring user class which has three propertiesclass user{public int Score { get; set; }public string Name { get; set; }public int Experience { get; set; }}// Main functionpublic static void Main(){//define two instances of the user class with different propertiesvar dummy0 = new user() { Score = 100, Name = "Michael Rick", Experience = 45 };var dummy1 = new user() { Score = 100, Name = "Michael Rick", Experience = 35 };var dummy2 = new user() { Score = 99, Name = "Michael Rick", Experience = 45 };//defining the function which has our switch expressionsstatic string check(user sample)=> sample switch{////case to check if the value of the Score property is 100 and Experience property is 45 years{Score:100, Experience:45} => "The user's Score is 100/100 and the user has an experience of 45 years!",//case to check if the value of the Score property is 100{Score:100} => "The user's Score is 100/100!",//case to check if the value of the Experience property is 45{Experience:45} => "The user has an experience of 45 years!",//Default case{Score:_, Name:_, Experience:_} => "Invalid input!"};//outputs return valueConsole.WriteLine("Dummy0: "+check(dummy0));Console.WriteLine("Dummy1: "+check(dummy1));Console.WriteLine("Dummy2: "+check(dummy2));}}
The above program outputs the following:
Dummy0: The user's Score is 100/100 and the user has an experience of 45 years!
Dummy1: The user's Score is 100/100!
Dummy2: The user has an experience of 45 years!
Free Resources