Pattern matching with objects
In Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, you were introduced to basic pattern matching. In this section, we will explore pattern matching in more detail.
Pattern-matching 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:
- In the
PacktLibraryNet2
project/folder, add a new file namedFlightPatterns.cs
. - If you use Visual Studio, in
FlightPatterns.cs
, delete the existing statements, including the class namedFlightPatterns
, because we will define multiple classes, and none match the name of the code file. - In
FlightPatterns.cs
, add statements to define three types of passenger with different properties, as shown in the following code:
// All the classes in this file will be defined in the following namespace.
namespace Packt.Shared;
public class Passenger...