In https://devblogs.microsoft.com/dotnet/c-9-0-on-the-record/#relational-patterns there's an example of using "nested switch expression":
DeliveryTruck t when t.GrossWeightClass switch
{
> 5000 => 10.00m + 5.00m,
< 3000 => 10.00m - 2.00m,
_ => 10.00m,
},
instead of:
DeliveryTruck t when t.GrossWeightClass > 5000 => 10.00m + 5.00m,
DeliveryTruck t when t.GrossWeightClass < 3000 => 10.00m - 2.00m,
DeliveryTruck _ => 10.00m,
But I can't get it to work... My full code:
public class DeliveryTruck {
public int GrossWeightClass { get; set; }
}
public class Class1 {
public decimal CalculateTollOriginal(object vehicle) =>
vehicle switch
{
DeliveryTruck t when (t.GrossWeightClass > 5000) => 10.00m + 5.00m,
DeliveryTruck t when (t.GrossWeightClass < 3000) => 10.00m - 2.00m,
DeliveryTruck t => 10.00m,
{ } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
null => throw new System.ArgumentNullException(nameof(vehicle))
};
public decimal CalculateTollNestedSwitch(object vehicle) =>
vehicle switch
{
DeliveryTruck t when t.GrossWeightClass switch
{
> 5000 => 10.00m + 5.00m,
< 3000 => 10.00m - 2.00m,
_ => 10.00m,
},
{ } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
null => throw new System.ArgumentNullException(nameof(vehicle))
};
}
And I'm getting compilation errors with dotnet 5.0.100:
C:\Users\pkruk\source\repos\CSharp9\PatternMatching2_NestedSwitch.cs(29,14): error CS1003: Syntax error, '=>' expected [C:\Users\pkruk\source\repos\CSharp9\CSharp9.csproj]
C:\Users\pkruk\source\repos\CSharp9\PatternMatching2_NestedSwitch.cs(29,14): error CS1525: Invalid expression term ',' [C:\Users\pkruk\source\repos\CSharp9\CSharp9.csproj]
Am I doing it wrong?
What you would need is
public decimal CalculateTollNestedSwitch(object vehicle) => vehicle switch
{
DeliveryTruck t => t.GrossWeightClass switch
{
> 5000 => 10.00m + 5.00m,
< 3000 => 10.00m - 2.00m,
_ => 10.00m,
},
{ } => throw new System.ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
null => throw new System.ArgumentNullException(nameof(vehicle))
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With