Pattern Matching with Objects
Learn about pattern matching by defining various flight passenger types and using switch expressions in C# 9 or later to calculate their flight costs.
Now, we will explore pattern matching. Through pattern matching, we will witness how C# elegantly handles different scenarios, making it a versatile tool for developers.
Defining flight passengers
In this example, we will define some classes that represent various types of passengers on a flight, and then we will use a switch
expression with pattern matching to determine the cost of their flight:
Step 1: In the PacktLibraryNetStandard2
project or folder, add a new file named FlightPatterns.cs
.
Step 2: In FlightPatterns.cs
, add statements to define three types of passenger with different properties, as shown in the following code:
Get hands-on with 1400+ tech skills courses.