Property Pattern in C#: What It Is and How to Use It
property pattern in C# lets you check if an object has specific property values directly inside a switch or if statement. It simplifies code by matching properties of an object without writing extra variable checks.How It Works
The property pattern in C# allows you to look inside an object and check its properties in a clean and readable way. Imagine you have a box and you want to know if it contains a red ball. Instead of opening the box and checking each item manually, the property pattern lets you ask directly, "Does this box have a ball that is red?"
In code, this means you can write conditions that match an object's properties without extra steps. The pattern looks like { PropertyName: value }, and you can use it inside switch or if statements to make decisions based on those properties.
Example
This example shows how to use the property pattern to check a person's age and city in a simple way.
public class Person { public string Name { get; set; } public int Age { get; set; } public string City { get; set; } } public class Program { public static void Main() { var person = new Person { Name = "Alice", Age = 30, City = "New York" }; if (person is { Age: >= 18, City: "New York" }) { System.Console.WriteLine("Adult living in New York"); } else { System.Console.WriteLine("Does not match criteria"); } } }
When to Use
Use the property pattern when you want to check one or more properties of an object quickly and clearly. It is helpful when you have complex objects and want to avoid writing many separate if statements for each property.
For example, in user input validation, filtering data, or handling different cases in a switch statement based on object details, the property pattern makes your code easier to read and maintain.
Key Points
- The property pattern matches object properties directly in conditions.
- It improves code readability by reducing nested checks.
- Works well with
switchexpressions andifstatements. - Supports relational patterns like
>=and<=inside property checks.
Key Takeaways
if or switch statements.