Property patterns help you check if an object has certain values in its properties easily and clearly.
0
0
Property patterns in C Sharp (C#)
Introduction
When you want to check if an object has specific property values without writing many if statements.
When you want to match objects based on their properties in a clean and readable way.
When you want to simplify complex conditions that involve multiple properties of an object.
Syntax
C Sharp (C#)
obj is { Property1: value1, Property2: value2, ... }You use is keyword followed by curly braces with property names and values.
This checks if obj has properties matching the given values.
Examples
This checks if the
person object has a Name property equal to "Alice".C Sharp (C#)
if (person is { Name: "Alice" }) { Console.WriteLine("Hello Alice!"); }
This checks if
point has X and Y properties both equal to 0.C Sharp (C#)
if (point is { X: 0, Y: 0 }) { Console.WriteLine("Point is at the origin."); }
This uses a relational pattern inside property pattern to check if
Quantity is greater than 0.C Sharp (C#)
if (order is { Status: "Shipped", Quantity: > 0 }) { Console.WriteLine("Order is shipped and has items."); }
Sample Program
This program creates a Person object and uses a property pattern to check if the Name is "Bob" and Age is 30. It prints a message if both match.
C Sharp (C#)
using System; class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { Person person = new() { Name = "Bob", Age = 30 }; if (person is { Name: "Bob", Age: 30 }) { Console.WriteLine("Found Bob who is 30 years old."); } else { Console.WriteLine("Person does not match."); } } }
OutputSuccess
Important Notes
Property patterns work well with records and classes that have readable properties.
You can combine property patterns with other patterns like relational patterns for more checks.
Summary
Property patterns let you check object properties easily and clearly.
Use them to simplify conditions that check multiple properties.
They improve code readability and reduce nested if statements.