Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //Only available in C# 8.0. Using .NET Core 3.1
- namespace switchStatementExample
- {
- public class Program
- {
- public static void Main()
- {
- var tollCalc = new TollCalculator();
- var car = new Car();
- var bus = new Bus();
- var taxi = new Taxi();
- Console.WriteLine($"The standard toll for a car is {tollCalc.CalculateToll(car)}");
- Console.WriteLine($"The standard toll for a bus is {tollCalc.CalculateToll(bus)}");
- Console.WriteLine($"The standard toll for a taxi is {tollCalc.CalculateToll(taxi)}");
- }
- }
- // Create new classes for different types of vehicles
- public class Car
- {
- public int passengers {get; set;}
- }
- public class Bus
- {
- public int passengers {get; set;}
- }
- public class Taxi
- {
- public int passengers {get; set;}
- }
- // Class to calculate the toll based on the type of object beign used.
- public class TollCalculator
- {
- public decimal CalculateToll(object vehicle) =>
- vehicle switch
- {
- Car c => 2.00m,
- Bus b => 10.00m,
- Taxi t => 4.00m,
- { } => throw new ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
- null => throw new ArgumentNullException(nameof(vehicle))
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement