DEV Community

Cover image for C# - Extended Property Patterns
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Extended Property Patterns

C# 10.0 introduced extended property patterns, enhancing the capabilities of pattern matching introduced in earlier versions. This feature allows for more concise and readable patterns, especially when dealing with complex types or nested objects.

Here’s how you can utilize extended property patterns in C#:

  1. Simplify Nested Property Patterns:
    With extended property patterns, you can directly reference nested properties in a pattern without the need for additional braces, making your patterns cleaner and more straightforward.

  2. Combine with Other Pattern Matching Features:
    These patterns can be combined with other pattern-matching features like positional patterns, var patterns, and logical patterns for powerful and expressive data querying.

Example:

public class Address
{
    public string City { get; set; }
    public string Country { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public Address Address { get; set; }
}

public static string GetPersonInfo(Person person) =>
    person switch
    {
        { Address.City: "New York", Address.Country: "USA" } => $"{person.Name} lives in New York, USA",
        { Address.Country: "Canada" } => $"{person.Name} lives in Canada",
        _ => "Location unknown"
    };

public static void Main()
{
    var person = new Person { Name = "Alice", Address = new Address { City = "New York", Country = "USA" } };
    Console.WriteLine(GetPersonInfo(person)); // Output: Alice lives in New York, USA
}
Enter fullscreen mode Exit fullscreen mode

In this example, the GetPersonInfo method uses extended property patterns to check the City and Country of a Person's Address. This approach reduces the verbosity and increases the readability of pattern matching, especially when dealing with nested properties.

Extended property patterns are a valuable addition to the pattern-matching toolbox in C#, making it easier and more intuitive to query and destructure complex data structures.

Top comments (0)