Home > OS >  C# nested property pattern expression
C# nested property pattern expression

Time:10-11

Is it possible to do pattern matching on type and sub/nested properties at the same time?

E.g. something like the following:

// Something like this would be nice
if (person is Person { Pet { Name: { } name2 }})
{
    Console.WriteLine(name2);
}

With class structure as follows

public class Person
{
    public object? Pet { get; set; }
}

public class Pet
{
    public string? Name { get; set; }
}

[Test]
public void Test()
{
    object person = GetPerson();

    // Example of current matching
    if(person is Person p && p.Pet is Pet pet && pet.Name is { } name)
    {
        Console.WriteLine(name);
    }
    
    // Sample inline method
    Person? GetPerson()
    {
        return new Person();
    }
}

Wondering if those 3 checks can be done in 1 line, without needing intermediary variables saved?

CodePudding user response:

In C# 8 it's possible. Credits to Rider which suggested to refactor it as:

if(person is Person {Pet: Pet {Name: { } name}})
{
    Console.WriteLine(name);
}

Starting from C# 8, there is Recursive Pattern Matching in language.

  • Related