Chapter 12. Deconstruction and pattern matching
This chapter covers
- Deconstructing tuples into multiple variables
- Deconstructing nontuple types
- Applying pattern matching in C# 7
- Using the three kinds of patterns introduced in C# 7
In chapter 11, you learned that tuples allow you to compose data simply without having to create new types and allowing one variable to act as a bag of other variables. When you used the tuples—for example, to print out the minimum value from a sequence of integers and then print out the maximum—you extracted the values from the tuple one at a time.
That certainly works, and in many cases it’s all you need. But in plenty of cases, you’ll want to break a composite value into separate variables. This operation is called deconstruction. That composite value may be a tuple, or it could be of another type—KeyValuePair, for example. C# 7 provides simple syntax to allow multiple variables to be declared or initialized in a single statement.
Deconstruction occurs in an unconditional way just like a sequence of assignments. Pattern matching is similar, but in a more dynamic context; the input value has to match the pattern in order to execute the code that follows it. C# 7 introduces pattern matching in a couple of contexts and a few kinds of patterns, and there will likely be more in future releases. We’ll start building on chapter 11 by deconstructing the tuples you’ve just created.