Skip to content

Checkpoint: A Money Type

The Course
•
40 min study

Using plain decimal for prices allows adding dollars to euros, and passing an amount where a tax rate was expected. A small value type makes those mistakes impossible to write. That's called avoiding primitive obsession, and it combines everything from today.

Operators

An operator is a static method with special syntax. Keep them obvious: + on money should add money. An implicit conversion happens silently, so only use one if it can't lose data or fail. An explicit conversion needs a cast in the code, which flags the risk.

Operators and conversions C#
var a = new Meters(2.5);
var b = new Meters(4);

Console.WriteLine((a + b).ToString());
Console.WriteLine(a < b);
double raw = a;
Console.WriteLine(raw);
Console.WriteLine(a);
Console.WriteLine(((Meters)7.0).ToString());

readonly record struct Meters(double Value)
{
    public static Meters operator +(Meters left, Meters right) => new Meters(left.Value + right.Value);

    public static bool operator <(Meters left, Meters right) => left.Value < right.Value;

    public static bool operator >(Meters left, Meters right) => left.Value > right.Value;

    public static implicit operator double(Meters meters) => meters.Value;

    public static explicit operator Meters(double value) => new Meters(value);

    public override string ToString() => $"{Value} m";
}
Check your prediction
Text
6.5 m
True
2.5
2.5
7 m

Look at the fourth line. Console.WriteLine(a) chose its double version, because the implicit conversion made that the best match, and the m disappeared. That's the risk of implicit conversions: they also apply when you didn't intend them. C# requires < and > to come as a pair, and == and != as a pair, for this reason: code expects both to exist.

Formatting and parsing

IParsable<T> is the standard interface for "can be parsed from a string", and IFormattable is the one for "takes a format". Generic code asks for the interface, not for a method name: a method declared where T : IParsable<T> can call T.TryParse only on types that implement IParsable<T>, so a TryParse you wrote on your own isn't enough. The interface wants two static methods, Parse(string, IFormatProvider?) and TryParse(string?, IFormatProvider?, out T). Here Rate implements it, so the same generic ParseOrDefault reads both a Rate and an int. Use InvariantCulture for anything saved or transmitted.

Round trip through text C#
#nullable enable
using System.Diagnostics.CodeAnalysis;
using System.Globalization;

foreach (string text in new[] { "12.5%", "12.5", "x%" })
{
    Console.WriteLine(Rate.TryParse(text, null, out Rate rate) ? rate.ToString() : $"bad: {text}");
}
Console.WriteLine(ParseOrDefault<Rate>("7%"));
Console.WriteLine(ParseOrDefault<int>("42"));

static T? ParseOrDefault<T>(string text) where T : IParsable<T> =>
    T.TryParse(text, CultureInfo.InvariantCulture, out T? value) ? value : default;

readonly record struct Rate(decimal Percent) : IParsable<Rate>
{
    public static bool TryParse([NotNullWhen(true)] string? text, IFormatProvider? provider, out Rate rate)
    {
        rate = default;
        if (text is null || !text.EndsWith('%') || !decimal.TryParse(text[..^1], NumberStyles.Number, CultureInfo.InvariantCulture, out decimal percent))
        {
            return false;
        }
        rate = new Rate(percent);
        return true;
    }

    public static Rate Parse(string text, IFormatProvider? provider) =>
        TryParse(text, provider, out Rate rate) ? rate : throw new FormatException($"bad rate: {text}");

    public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Percent}%");
}
Check your prediction
Text
12.5%
bad: 12.5
bad: x%
7%
42

Build it yourself

Exercise

Money

Write a readonly record struct Money(decimal Amount, string Currency) that implements IComparable<Money>:

  • + and - work on matching currencies, and otherwise throw InvalidOperationException with currency mismatch.
  • * multiplies by a decimal, rounding to two places with Math.Round(value, 2, MidpointRounding.ToEven).
  • CompareTo throws on a mismatch.
  • Split(int parts) returns a Money[] whose amounts differ by at most one cent and which adds up exactly to the original. The first parts get the extra cents, which for a negative amount moves them further from zero. An amount with a fraction of a cent can't be split exactly, so Split refuses it with InvalidOperationException.
  • ToString prints 10.00 USD, with two decimal places.
  • TryParse(string, out Money) reads text like 10.00 USD.

Print the sum of 10 USD and 2.50 USD, the result of 10 USD * 0.333, the three parts of 10 USD, -10 USD and 0.02 USD, the refusal to split 1.234 USD, the largest of a small list using Max, and the parse results for 5.5 EUR and 5.5. Show the mismatch being refused.

This is the longest exercise of the day, so build it in pieces and run it after each one. Start with the core: ToString, +, -, * and TryParse. If you run out of time, stop there and come back to CompareTo and Split later: Split is the part that takes longest, because of the negative and fraction-of-a-cent cases.

When it works, it prints:

Text
12.50 USD
3.33 USD
3.34 USD, 3.33 USD, 3.33 USD
-3.34 USD, -3.33 USD, -3.33 USD
0.01 USD, 0.01 USD, 0.00 USD
amount has a fraction of a cent
10.00 USD
5.50 EUR
False
currency mismatch
Your workspace C#
using System.Globalization;

Console.WriteLine(10.5m.ToString("F2", CultureInfo.InvariantCulture));
Hint 1: the idea

For Split, work in whole cents. Integer division gives the base share, and the remainder says how many parts get one more cent. In C#, the remainder takes the sign of the amount, so try a negative amount early.

Hint 2: a first step

Write ToString and + with a private helper that checks currencies, then use that helper in - and CompareTo.

Show one solution
C#
#nullable enable

using System.Globalization;

var ten = new Money(10m, "USD");

Console.WriteLine(ten + new Money(2.5m, "USD"));
Console.WriteLine(ten * 0.333m);
Console.WriteLine(string.Join(", ", ten.Split(3)));
Console.WriteLine(string.Join(", ", new Money(-10m, "USD").Split(3)));
Console.WriteLine(string.Join(", ", new Money(0.02m, "USD").Split(3)));

try
{
    new Money(1.234m, "USD").Split(2);
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

Console.WriteLine(new[] { new Money(1m, "USD"), ten, new Money(3m, "USD") }.Max());
Console.WriteLine(Money.TryParse("5.5 EUR", out Money parsed) ? parsed.ToString() : "bad");
Console.WriteLine(Money.TryParse("5.5", out _));

try
{
    _ = ten + new Money(1m, "EUR");
}
catch (InvalidOperationException e)
{
    Console.WriteLine(e.Message);
}

readonly record struct Money(decimal Amount, string Currency) : IComparable<Money>
{
    private void Require(Money other)
    {
        if (Currency != other.Currency)
        {
            throw new InvalidOperationException("currency mismatch");
        }
    }

    public static Money operator +(Money left, Money right)
    {
        left.Require(right);
        return left with { Amount = left.Amount + right.Amount };
    }

    public static Money operator -(Money left, Money right)
    {
        left.Require(right);
        return left with { Amount = left.Amount - right.Amount };
    }

    public static Money operator *(Money money, decimal factor)
    {
        return money with { Amount = Math.Round(money.Amount * factor, 2, MidpointRounding.ToEven) };
    }

    public int CompareTo(Money other)
    {
        Require(other);
        return Amount.CompareTo(other.Amount);
    }

    public Money[] Split(int parts)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(parts, 1);
        decimal exact = Amount * 100m;
        if (exact != decimal.Truncate(exact))
        {
            throw new InvalidOperationException("amount has a fraction of a cent");
        }
        long cents = (long)exact;
        long share = cents / parts;
        long extra = Math.Abs(cents % parts);
        int step = Math.Sign(cents);
        var result = new Money[parts];
        for (int i = 0; i < parts; i++)
        {
            result[i] = this with { Amount = (share + (i < extra ? step : 0)) / 100m };
        }
        return result;
    }

    public static bool TryParse(string text, out Money money)
    {
        money = default;
        string[] parts = text.Split(' ');
        if (parts.Length != 2 || !decimal.TryParse(parts[0], NumberStyles.Number, CultureInfo.InvariantCulture, out decimal amount))
        {
            return false;
        }
        money = new Money(amount, parts[1]);
        return true;
    }

    public override string ToString() => $"{Amount.ToString("F2", CultureInfo.InvariantCulture)} {Currency}";
}
Text
12.50 USD
3.33 USD
3.34 USD, 3.33 USD, 3.33 USD
-3.34 USD, -3.33 USD, -3.33 USD
0.01 USD, 0.01 USD, 0.00 USD
amount has a fraction of a cent
10.00 USD
5.50 EUR
False
currency mismatch

Multiplying 10 by 0.333 and multiplying by three would lose a cent, which is why Split exists as its own operation. Rounding rules for real money vary by country and business, so make the choice explicit.

Was this article helpful?

Your response is saved on this device.