Skip to content

Property pattern

Context: The property pattern matches an object’s properties against nested patterns.

public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Point p = new Point { X = 10, Y = 20 };
if (p is { X: 10, Y: 20 })
{
Console.WriteLine("Point (10,20)");
}
string quadrant = p switch
{
{ X: > 0, Y: > 0 } => "Q1",
{ X: < 0, Y: > 0 } => "Q2",
{ X: < 0, Y: < 0 } => "Q3",
{ X: > 0, Y: < 0 } => "Q4",
_ => "On axis"
};

Validation rules: Use property pattern in a switch expression to validate complex objects without multiple if statements.

Example: In FluentValidation, you could implement custom rules using property pattern.