Chapter 8. Matching with Patterns
Historically, developers have implemented business rules with various logical checks and comparisons. Sometimes the rules are complex—naturally leading to code that’s difficult to write, read, and maintain. Think about how often you’ve encountered multibranch logic with multivariate comparisons and multiple levels of nesting.
To help ease this complexity, modern programming languages have begun introducing pattern matching—features of the language that help match facts to results with declarative syntax. In C#, pattern matching manifests as a growing list of features added in each new version, especially from C# 7 and later.
The theme of this chapter revolves around hotel scheduling and using patterns for business rules. The criteria is usually around a type of customer such as Bronze, Silver, or Gold, with Gold being the highest level because those customers have more points from more frequent hotel stays.
This chapter discusses pattern matching for properties, tuples, and types. There’s also a couple of sections on logical operations and how they enable and simplify multiconditional patterns. Surprisingly, C# had some form of pattern matching since v1.0. The first section of this chapter discusses the is
and as
operators and shows the new enhancements to the is
operator.
8.1 Converting Instances Safely
Problem
Your legacy code is weakly typed, relies on procedural patterns, and needs to be refactored.
Solution
Here’s an interface and implementing ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.