Simplified property pattern matching expression for nested properties · dotnet/csharplang · Discussion #4114 (original) (raw)

Yesterday I stumbled upon a scenario where I needed to inspect a few properties on a given "response" object and respond to them accordingly. The problem was that some of the properties were nested multiple levels deep into the object graph, while others were in the root of the object.

This is an example:

return response switch { { Authentication: { Status: not Success } } => DoSomething(), { Status: not Success } => DoSomethingElse(), { ContextData: { ApplicationData: { Check1: { Code: Blocked } } } } => DoAThirdThing(), { ContextData: { ApplicationData: { Check2: { Code: InvalidIdentificationDocument, Description: string message } } } } => DoAFourthThing(message), { ContextData: { ApplicationData: { Check2: { Code: InformationMismatch, Description: string message } } } } => DoAFifthThing(message), { ResponseInfo: { CurrentQueue: not null } } => DoASixthThing(), _ => DoDefault(), };

As you can see, it becomes very unwieldy very fast when deep nesting levels are required in the matches.

I'd like to propose something like this instead:

return response switch { { Authentication.Status: not Success } => DoSomething(), { Status: not Success } => DoSomethingElse(), { ContextData.ApplicationData.Check1.Code: Blocked } => DoAThirdThing(), { ContextData.ApplicationData.Check2: { Code: InvalidIdentificationDocument, Description: string message } } => DoAFourthThing(message), { ContextData.ApplicationData.Check2: { Code: InformationMismatch, Description: string message } } => DoAFifthThing(message), { ResponseInfo.CurrentQueue: not null } => DoASixthThing(), _ => DoDefault(), };

At a first glance, it seems like an easy to implement syntactic sugar that doesn't appear to create any conflicts with existing language terms, as it relies on the . for navigation on something that doesn't support it today.

While incredibly convoluted, this example is actually closely based on a real use-case on my side, as I had to deal with several possible outcomes happening from a single external service response. I believe the service itself is not that well designed, but that's beside the point.