This article focuses on extending the property pattern to the next level. Refer prerequisites section for the previous toll fare example used, and the following article extends that example further.
Please review the article example below, which calculates a toll fare based on the vehicle type.
Advance Property Pattern C# 8.0
The article describes how pattern matching provides an effective way to utilize and process that data in forms that…*medium.com
The toll authority wants to add time-sensitive peak pricing for the final feature.
Let’s proceed with identifying each column of the reference table above.
Firstly the program should be aware of whether a particular day is a weekday or weekend. Refer new switch syntax.
The above code makes use “System.DaysOfWeek” enum.
public enum DayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6
}
Firstly, the distinct time slots available.
private enum TimeSlots
{
MorningPeak,
Daytime,
EveningPeak,
Overnight
}
Now let’s identify the time slots using switch syntax with time in hours.
As there are two possible values of direction, it can directly be used as a boolean flag, i.e., if ‘true’ means inbound and if ‘false’ means outbound.
True => inbound => Into the city
False => outbound => Out of the city
The alternative is to create an enum and add switch syntax, similar to what we have done above.
After all table columns are identified, the below switch expression with the tuple pattern calculates the toll premium.
Refer to pattern-matching syntax with single & multiple property classes. Link
The switch expression.
var costInbound = PeakPremium.CalculatePeakTimePremium(DateTime.Now, true);
var costOutbound = PeakPremium.CalculatePeakTimePremium(DateTime.Now, false);
Console.WriteLine("Charges {0} for {1}",costInbound,DateTime.Now);
Console.WriteLine("Charges {0} for {1}", costOutbound, DateTime.Now);
Charges 1.50 for 9/8/2020 12:05:29 PM
Charges 1.50 for 9/8/2020 12:05:29 PM
ssukhpinder/PropertyPatternExample
Thank you for reading. I hope you like the article..!!
Also published here.