BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News C# 8 Pattern Matching Enhancements

C# 8 Pattern Matching Enhancements

This item in japanese

C# 7 laid the groundwork for pattern matching, but a lot of features had to be left on the cutting room floor. With the extra time C# 8 needs, many of these are being picked up.

Positional Pattern Matching

Consider this rather verbose pattern using C# 7 syntax.

case Rectangle r when r.Length == 10 && r.Width == 10: return "Found 10x10 rectangle";

By leveraging the deconstructor feature, the new positional pattern match makes the feature much less verbose.

case Rectangle (10, 10): return "Found 10x10 rectangle";

This feature will also be supported with anonymous tuples. This is referred to as a “tuple pattern”. You can see an example of this in Mad’s article Do more with patterns in C# 8.0.

Property Pattern Matching

The positional pattern is concise, but it only works if you happen to have a suitable Deconstruct method. When you don’t, you can use a property pattern instead.

case Rectangle {Width : 10 }: return "Found a rectangle with a width of 10";

Support for indexed properties are being considered as well, but the specifics have not been determined.

Deconstructor Improvements

Another idea being considered under the Open LDM Issues in Pattern-Matching ticket is allowing multiple Deconstruct methods with the same number of parameters. In addition to having different types, the parameters must be named differently.

ITuple Pattern Matching

The ITuple interface, introduced in .NET 4.7.1 and .NET Core 2.0, raises several questions in C# 8. The basic idea is that if an object implements this interface, then it can participate in pattern matching. Three scenarios are under consideration regarding when this goes into effect.

if (x is ITuple(3, 4)) // (1) permitted?
if (x is object(3, 4)) // (2) permitted?
if (x is SomeTypeThatImplementsITuple(3, 4)) // (3) permitted?

A related question is if a class implements ITuple and there is a Deconstruct extension method, which takes priority? Ideally, they would return the same values, but a tie breaker is needed when that’s not the case.

Rate this Article

Adoption
Style

BT