visit
Prerequisites:
Please review the articles below for a basic understanding of the C# 8.0 concepts required in this article.
Let’s get started
Let’s take an example of Toll Calculator and see how pattern matching helps to write an algorithm for that.
public static int TollFare(Object vehicleType) => vehicleType switch
{
Car c => 100,
DeliveryTruck d => 200,
Bus b => 150,
Taxi t => 120,
null => 0,
{ } => 0
};
var car = new Car();
var taxi = new Taxi();
var bus = new Bus();
var truck = new DeliveryTruck();
Console.WriteLine($"The toll for a car is {TollFare(car)}");
Console.WriteLine($"The toll for a taxi is {TollFare(taxi)}");
Console.WriteLine($"The toll for a bus is {TollFare(bus)}");
Console.WriteLine($"The toll for a truck is {TollFare(truck)}");
The toll for a car is 100
The toll for a taxi is 120
The toll for a bus is 150
The toll for a truck is 200
Refer to pattern-matching syntax with single & multiple property classes.
Car { PassengerCount: 0 } => 100 + 10,
Car { PassengerCount: 1 } => 100,
Car { PassengerCount: 2 } => 100 - 10,
Car c => 100 - 20,
Taxi {Fare:0 }=>100+10,
Taxi { Fare: 1 } => 100,
Taxi { Fare: 2 } => 100 - 10,
Taxi t => 100 - 20,
Bus b when ((double)b.RidersCount / (double)b.Capacity) < 0.50 => 150 + 30,
Bus b when ((double)b.RidersCount / (double)b.Capacity) > 0.90 => 150 - 40,
Bus b => 150,
DeliveryTruck t when (t.Weight > 5000) => 200 + 100,
DeliveryTruck t when (t.Weight < 3000) => 200 - 20,
DeliveryTruck t => 200,
var car1 = new Car{ PassengerCount=2};
var taxi1 = new Taxi { Fare = 0 };
var bus1 = new Bus { Capacity = 100, RidersCount = 30 };
var truck1 = new DeliveryTruck { Weight = 30000 };
Console.WriteLine($"The toll for a car is {OccupancyTypeTollFare(car1)}");
Console.WriteLine($"The toll for a taxi is {OccupancyTypeTollFare(taxi1)}");
Console.WriteLine($"The toll for a bus is {OccupancyTypeTollFare(bus1)}");
Console.WriteLine($"The toll for a truck is {OccupancyTypeTollFare(truck1)}");
The toll for a car is 90
The toll for a taxi is 110
The toll for a bus is 180
The toll for a truck is 300
“Pattern matching makes code more readable and offers an alternative to object-oriented techniques when you can’t add code to your classes.”