Microsoft has launched a property pattern in C# 8.0 version, which is an excellent way to compare object properties.
Please understand the new switch syntax introduced in C# 8.0, which helps to understand the current article example much better. New Switch syntax with C# 8.0
The property pattern permits you to match on properties of the object measured.
public class Calculate
{
public string multiplyBy { get; set; }
}
The following example covers a new switch case with property class, where the property variable is accessed inside {} braces. So if the string property value is ten times, then multiply the price by ten, and return the price using lambda expressions.
The “_” symbol represents the default case. **Refer new switch syntax**
private static decimal ComputeOverallPrice(Calculate calculate, decimal price) =>
calculate switch
{
{ multiplyBy: "10 times" } => 10 * price,
{ multiplyBy: "5 times" } => 5 * price,
{ multiplyBy: "20 times" } => 20 * price,
_ => 0M
};
Let us consider a class with multiple properties and utilize those in pattern matching.
public class CalculateMultipleProperty
{
public string multiplyBy { get; set; }
public bool isAdditionApplicable { get; set; }
}
So basically, if the second property, i.e., “isAdditionApplicable,” is true, we add 100 more to result in price. The following example covers a new switch case with property class, where the property variable is accessed inside {} braces.
Multiple properties are accessed comma-separated inside the {} braces.
The “_” symbol represents the default case. **Refer new switch syntax**
private static decimal ComputeOverallPriceMultiple(CalculateMultipleProperty calculate, decimal price) =>
calculate switch
{
{multiplyBy:"10 times",isAdditionApplicable:true}=>10*price + 100,
{multiplyBy:"5 times",isAdditionApplicable:true}=>5*price + 50,
{multiplyBy:"20 times",isAdditionApplicable:true}=>20*price + 70,
_ => 0M
};
The below sample contains an example of both single & multiple property pattern matching. PropertyPatternExample
Advance Property Pattern C# 8.0
Thank you for reading. Keep visiting and share this in your network. Please put your thoughts and feedback in the comments section.
C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.