Advertisement
jyoung12387

Switch Expression - Pattern Matching

Mar 20th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | None | 0 0
  1. using System;
  2.  
  3. //Only available in C# 8.0. Using .NET Core 3.1
  4.  
  5. namespace switchStatementExample
  6. {
  7.                    
  8.     public class Program
  9.     {
  10.         public static void Main()
  11.         {
  12.             var tollCalc = new TollCalculator();
  13.            
  14.             var car = new Car();
  15.             var bus = new Bus();
  16.             var taxi = new Taxi();
  17.            
  18.             Console.WriteLine($"The standard toll for a car is {tollCalc.CalculateToll(car)}");
  19.             Console.WriteLine($"The standard toll for a bus is {tollCalc.CalculateToll(bus)}");
  20.             Console.WriteLine($"The standard toll for a taxi is {tollCalc.CalculateToll(taxi)}");
  21.         }
  22.     }
  23.    
  24.     // Create new classes for different types of vehicles
  25.    
  26.     public class Car
  27.     {
  28.         public int passengers {get; set;}
  29.     }
  30.    
  31.     public class Bus
  32.     {
  33.         public int passengers {get; set;}  
  34.     }
  35.    
  36.     public class Taxi
  37.     {
  38.         public int passengers {get; set;}  
  39.     }
  40.    
  41.     // Class to calculate the toll based on the type of object beign used.
  42.    
  43.     public class TollCalculator
  44.     {
  45.         public decimal CalculateToll(object vehicle) =>
  46.             vehicle switch
  47.             {
  48.                 Car c => 2.00m,
  49.                 Bus b => 10.00m,
  50.                 Taxi t => 4.00m,
  51.                 { } => throw new ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
  52.                 null => throw new ArgumentNullException(nameof(vehicle))
  53.             };
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement