Select Page

A shipping rule can match an order’s destination and membership tier yet still fail its weight allowance. A when guard lets that order continue to the ordinary price bands. This tutorial builds one switch expression over weight, zone and tier, then checks nine hand-computed prices.

Write down the pricing policy

These are invented teaching prices in currency units. Weight is in kilograms, with supported weights greater than zero and no more than 20 kg. Zones are the exact strings Local and Remote; tiers are Standard and Gold.

Ordinary rates, used when no Gold allowance applies
Weight Local Remote
Up to 2 kg 5 15
Over 2 through 5 kg 8 20
Over 5 through 20 kg 8 + 2 per kg above 5 20 + 3 per kg above 5

Gold orders within a shared 2 kg allowance cost zero locally and 10 remotely. Gold orders above that allowance pay the ordinary rate. Apply the allowance first. The higher-weight formulas charge fractional kilograms proportionally; there is no rounding up to a whole kilogram, tax, or real carrier integration.

Run the complete nine-order fixture

Use a .NET 10 SDK and an ordinary console project. The program below was compiled targeting net10.0 in a pinned offline SDK container, with nullable analysis, implicit usings and warnings treated as errors. The successful build reported zero warnings and errors. These are established language features, not a claim of new .NET 10 syntax.

dotnet new console --framework net10.0 --name ShippingGuards
cd ShippingGuards

Replace the entire generated Program.cs with this complete program. Leave the intentionally unreachable arm commented out for the successful run.

using System;
using System.Globalization;

public static class Program
{
    public static decimal Shipping(decimal weight, string zone, string tier,
        decimal freeWeightLimit) => (weight, zone, tier) switch
    {
        (<= 0m or > 20m, _, _) => throw new ArgumentOutOfRangeException(nameof(weight)),
        (_, not ("Local" or "Remote"), _) => throw new ArgumentException("Unknown zone."),
        (_, _, not ("Standard" or "Gold")) => throw new ArgumentException("Unknown tier."),
        (var w, "Local", "Gold") when w <= freeWeightLimit => 0m,
        (<= 2m, "Local", _) => 5m,
        // (1m, "Local", "Standard") => 99m, // CS8510: The pattern is unreachable.
        (<= 5m, "Local", _) => 8m,
        (var w, "Local", _) => 8m + (w - 5m) * 2m,
        (var w, "Remote", "Gold") when w <= freeWeightLimit => 10m,
        (<= 2m, "Remote", _) => 15m,
        (<= 5m, "Remote", _) => 20m,
        (var w, "Remote", _) => 20m + (w - 5m) * 3m,
    };

    public static void Main()
    {
        CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
        const decimal freeWeightLimit = 2m;
        (decimal Weight, string Zone, string Tier, decimal Expected)[] orders =
        {
            (2m, "Local", "Gold", 0m),
            (2.1m, "Local", "Gold", 8m),
            (2m, "Local", "Standard", 5m),
            (5m, "Local", "Standard", 8m),
            (6m, "Local", "Standard", 10m),
            (2m, "Remote", "Gold", 10m),
            (2.1m, "Remote", "Gold", 20m),
            (2m, "Remote", "Standard", 15m),
            (6m, "Remote", "Standard", 23m)
        };
        Console.WriteLine("kg | zone | tier | cost | expected");
        foreach (var order in orders)
        {
            decimal actual = Shipping(order.Weight, order.Zone, order.Tier, freeWeightLimit);
            if (actual != order.Expected)
                throw new InvalidOperationException($"Wrong cost for {order}.");
            Console.WriteLine($"{order.Weight:0.0} | {order.Zone} | {order.Tier} | {actual:0.00} | {order.Expected:0.00}");
        }
        Console.WriteLine("All 9 shipping assertions passed.");
    }
}
dotnet run -p:TreatWarningsAsErrors=true

The checked application output is:

kg | zone | tier | cost | expected
2.0 | Local | Gold | 0.00 | 0.00
2.1 | Local | Gold | 8.00 | 8.00
2.0 | Local | Standard | 5.00 | 5.00
5.0 | Local | Standard | 8.00 | 8.00
6.0 | Local | Standard | 10.00 | 10.00
2.0 | Remote | Gold | 10.00 | 10.00
2.1 | Remote | Gold | 20.00 | 20.00
2.0 | Remote | Standard | 15.00 | 15.00
6.0 | Remote | Standard | 23.00 | 23.00
All 9 shipping assertions passed.

Every expected price is stored as a literal in the fixture rather than calculated by calling the pricing function. A mismatch throws before the final success message. Finishing all nine comparisons normally exits with code 0. Invariant culture makes the displayed decimal separator consistent.

Separate the tuple pattern from its guard

The switch input contains three positions: weight, zone and tier. String constants match named categories; relational patterns compare weight with fixed boundaries; var w captures weight for the guard or result formula. An underscore ignores that position. The first three arms reject unsupported input shapes. Microsoft describes these building blocks in the patterns reference, including matching tuple inputs under positional patterns.

The allowance is a method parameter. A relational pattern needs a constant boundary, so the Gold arms capture weight and compare it with that parameter in a Boolean guard. The caller supplies 2 here; this fixture does not test other allowance configurations. See Microsoft’s case-guard documentation.

The selected arm must satisfy both its pattern and its guard. Selection follows source order. For the first row, the local Gold pattern matches and the allowance succeeds, producing zero. At 2.1 kg the same Gold pattern matches but its guard fails; the local 2 kg band also fails, so the 5 kg band returns 8. Remote Gold similarly changes from 10 at 2 kg to 20 at 2.1 kg. This behavior follows the documented arm-selection rules.

Place each membership exception above its ordinary bands. Moving the local 2 kg band above the Gold arm would charge a qualifying member 5 instead of zero. The compiler does not know which pricing policy you intended; the first fixture row protects that decision. For a related use of ordered rules, read pattern matching for first-error validation.

Make the unreachable arm fail deliberately

The commented arm targets a 1 kg Local Standard order. Uncomment that one line and build the same project:

dotnet build -p:TreatWarningsAsErrors=true

A separate isolated fixture compiled that exact variation and required failure with CS8510, empty application stdout, and this diagnostic:

error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match.

The preceding unguarded local 2 kg arm already includes every input of that 1 kg arm. That is the coverage responsible for the error. The earlier Gold guard is not the reason: a guard can fail, as the 2.1 kg rows demonstrate. Microsoft documents rejection of arms covered by earlier arms. Comment the line again to restore the runnable fixture.

Keep boundary checks beside the rules

The nine rows exercise both successful and failed Gold guards, the 2 kg boundary, the local 5 kg boundary, and both above-5 kg formulas. A 6 kg Local order is 8 + 2 × 1 = 10; its Remote counterpart is 20 + 3 × 1 = 23. Those independent calculations make the expected values reviewable.

This fixture samples valid orders. It does not test the rejection branches, every decimal weight, alternative allowances, or a currency rounding policy. Add expected cases for those contracts before expanding the calculator. For more on coverage diagnostics, continue with switch expressions and exhaustive handling; for a finite tuple rule table, try the 25-round tuple-switch exercise.

Share This