Object-Oriented C# · Lesson 10

Modeling states

Paid and Refunded are different states of one payment.

How it works

state starts as Paid with amount 12. Describe matches Paid and prints paid 12. The next assignment stores a Refunded value with amount 3. The same method matches Refunded and prints refunded 3. Both classes share the Payment base, and the switch has an arm for each one.

A working example

Payment state = new Paid(12);
Console.WriteLine(Describe(state));
state = new Refunded(3);
Console.WriteLine(Describe(state));

string Describe(Payment state) => state switch
{
    Paid paid => "paid " + paid.Amount,
    Refunded refunded => "refunded " + refunded.Amount,
    _ => "unknown"
};

abstract class Payment { }

sealed class Paid : Payment
{
    public int Amount { get; }
    public Paid(int amount) { Amount = amount; }
}

sealed class Refunded : Payment
{
    public int Amount { get; }
    public Refunded(int amount) { Amount = amount; }
}

Try this
Match the state you stored, then read its amount.