What’s New in C# 10: Simplify Nested Property Pattern Code

This is part of a series on the new features introduced with C# 10.

Pattern matching in C# was first introduced in C# 7 and has been added to in later versions.

C# 8 added property pattern matching to allow you to match on the values of properties and fields. Prior to C# 10, property pattern matching with simple (non-nested) types was fine but if the thing you were matching was in a nested property the syntax was slightly clumsy:

public record CurrencyExchangeRate(string SourceCurrencyCode,
                                   string DestinationCurrencyCode,
                                   decimal ExchangeRate);

public record Trade(int CustomerId, CurrencyExchangeRate ExchangeRate);

In the preceding code we have a Trade that has a nested CurrencyExchangeRate, in C# 9 if we wanted to match on this nested CurrencyExchangeRate such as the SourceCurrencyCode, we’d have to use the following syntax:

public static bool IsRelatedToAustralia(Trade trade) =>
    trade is { ExchangeRate: { SourceCurrencyCode: "AUD" } } or
             { ExchangeRate: { DestinationCurrencyCode: "AUD" } };

Notice the extra nested {} to access the nested currency codes.

From C# 10 you can access nested properties directly which makes the code a little more readable, for example:

static bool IsRelatedToAustralia(Trade trade) =>
    trade is { ExchangeRate.SourceCurrencyCode: "AUD" } or
             { ExchangeRate.DestinationCurrencyCode: "AUD" };

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Add comment

Loading