Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
The property pattern is a pattern matching construct in C# that enables you to match an expression’s properties or fields against nested patterns. It evaluates to true if the input expression is non-null and every specified property or field matches its corresponding pattern.
Syntax
The property pattern is defined using curly braces { } containing a comma-separated list of property names, a colon :, and the nested pattern to match against that property.
{ Property1: <Pattern>, Property2: <Pattern> }
It is most frequently combined with a type pattern to ensure the object is of a specific type before evaluating its properties:
<Type> { Property1: <Pattern> }
Core Mechanics
Implicit Null Checking
A property pattern inherently guarantees that the input is not null. If the input expression evaluates to null, the pattern immediately returns false without throwing a NullReferenceException. Consequently, an empty property pattern is commonly used as a concise non-null check.
// Evaluates to true if obj is not null
bool isNotNull = obj is { };
Constant and Relational Matching
Properties can be matched against constant values or evaluated using relational patterns (<, >, <=, >=).
// Matches if obj is a Person, Age is 30 or greater, and Status is "Active"
bool match = obj is Person { Age: >= 30, Status: "Active" };
Variable Capture (Declaration Pattern)
You can extract property values directly into local variables during the match by combining the property pattern with a declaration pattern.
// If obj is a Person, extracts the Name property into the 'personName' variable
if (obj is Person { Name: string personName })
{
Console.WriteLine(personName);
}
// Using 'var' for implicit typing during capture
bool match = obj is Person { Age: var extractedAge };
Nested Property Patterns
Because the right side of the colon accepts any valid C# pattern, property patterns can be nested recursively to evaluate complex object graphs.
// Matches if the Person's Address property has a City property equal to "Seattle"
bool match = obj is Person { Address: { City: "Seattle" } };
Extended Property Patterns (C# 10+)
Starting in C# 10, you can reference nested properties directly using dot notation, eliminating the need for nested curly braces. This provides a more concise syntax for deep property evaluation.
// Functionally identical to the nested example above
bool match = obj is Person { Address.City: "Seattle" };
Logical Combinators
Property patterns fully support logical combinators (and, or, not) within the nested pattern evaluation.
// Matches if Age is between 18 and 65, and Name is NOT null
bool match = obj is Person { Age: >= 18 and <= 65, Name: not null };
Master C# with Deep Grasping Methodology!Learn More