skip to content

In C#, how do you let your own Money struct flow through a generic Sum<T>, and why constrain T to IAdditionOperators<T, T, T> rather than INumber<T>?

level: seniorimportance: should knowfreq 30%

answer

  1. implement the operator interfaces
  2. TSelf names the implementing type
  3. a starting value without INumber
  4. INumber<T> means about sixty members
  5. constrain to what the body uses

basics

~20 s

Implement the narrow interfaces the method needs, Money : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>, with a static operator + and AdditiveIdentity. INumber<T> would force about sixty members, including Parse and Money * Money, that money does not have.

solid answer

~50 s

`Sum<T>` needs only a starting value and `+`, so constrain it to `where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>` and write `T total = T.AdditiveIdentity; total += item;`. The built-in numeric types already implement both, and `Money` joins by declaring them and supplying `public static Money operator +(Money left, Money right)` and `public static Money AdditiveIdentity`. The first type argument is TSelf, the implementing type, which lets the interface speak about `Money + Money` returning `Money` instead of an interface-typed value; the interface even constrains it to itself. Constraining to `INumber<T>` instead would demand everything a real number has: an empty struct declaring it reports 61 CS0535 errors on the .NET 10 SDK, including `Money * Money`, `Parse` and `One`, which you would have to fake. If `Money` forgets `IAdditiveIdentity`, `Sum<Money>` fails at compile time with CS0315.

code

csharp · 25 lines
csharp
using System.Globalization;
using System.Numerics;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Money[] lines = [new(10.50m), new(4.25m)];
Console.WriteLine(Sum<Money>(lines));
Console.WriteLine(Sum<int>([1, 2, 3]));
Console.WriteLine(Sum<decimal>([0.1m, 0.2m]));

static T Sum<T>(ReadOnlySpan<T> items)
    where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>
{
    T total = T.AdditiveIdentity;
    foreach (T item in items)
        total += item;
    return total;
}

readonly record struct Money(decimal Amount)
    : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>
{
    public static Money AdditiveIdentity => new(0m);
    public static Money operator +(Money left, Money right) => new(left.Amount + right.Amount);
    public override string ToString() => Amount.ToString("0.00");
}

go deeper

for a junior

Recall that the numeric interfaces come in small pieces, such as IAdditionOperators for + and IAdditiveIdentity for a starting value, and that your own struct can implement them.

for a middle

Explain what TSelf, TOther and TResult mean in IAdditionOperators<TSelf, TOther, TResult> and why the implementations must be static.

for a senior

Show that you pick the narrowest constraint the body uses, explain why INumber<T> would shut out Money, and know which compile errors each mistake produces.

for a principal

Treat each interface in a public where clause as a demand on every consumer's types, and choose them so domain types can join without faking members.

## The operator interfaces are the building blocks `INumber<T>` is not one big contract written from scratch; it is a stack of small interfaces in `System.Numerics`. `INumberBase<TSelf>` inherits, among others, `IAdditionOperators`, `IAdditiveIdentity`, `ISubtractionOperators`, `IMultiplyOperators`, `IDivisionOperators`, `IMultiplicativeIdentity`, `IEqualityOperators`, `IIncrementOperators`, `IDecrementOperators`, `ISpanParsable` and `ISpanFormattable`. `INumber<TSelf>` adds `IComparisonOperators`, `IModulusOperators` and `IComparable<TSelf>`. Every built-in numeric type implements the whole stack, but a generic method should ask only for the layers its body uses. | What the method body uses | Constraint that grants it | |---|---| | `a + b` | `IAdditionOperators<T, T, T>` | | `T.AdditiveIdentity` as the starting total | `IAdditiveIdentity<T, T>` | | `a < b`, `a > b` | `IComparisonOperators<T, T, bool>` | | `a * rate` with a `decimal` rate | `IMultiplyOperators<T, decimal, T>` | | `T.Zero`, `T.One`, `T.CreateChecked`, `T.Parse` and the rest | `INumberBase<T>` or `INumber<T>` | ## What TSelf does The declaration in the .NET source is: ```csharp public interface IAdditionOperators<TSelf, TOther, TResult> where TSelf : IAdditionOperators<TSelf, TOther, TResult>? { static abstract TResult operator +(TSelf left, TOther right); static virtual TResult operator checked +(TSelf left, TOther right) => left + right; } ``` - **TSelf** is the type that implements the interface, and the constraint makes it refer to itself. That self-reference is what lets the operator's signature mention the real type, `Money + Money`, rather than an interface type that would box the value and lose its static type. - C# requires one operand of an operator declared in an interface to be the containing type or a type parameter constrained to it (CS8924 otherwise); TSelf is that type parameter. - **TOther** and **TResult** let operands and results differ, so `Money` can implement `IMultiplyOperators<Money, decimal, Money>` for scaling by a rate without pretending that `Money * Money` means anything. ## Implementing it on Money ```csharp readonly record struct Money(decimal Amount) : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money> { public static Money AdditiveIdentity => new(0m); public static Money operator +(Money left, Money right) => new(left.Amount + right.Amount); } ``` Points that come up in review: 1. The implementations are **static**. A non-static member cannot implement a static abstract one (CS8928). 2. A public `operator +` serves both worlds: generic code reaches it as `T`'s operator and ordinary code writes `a + b`. 3. A member you want off the public surface can be implemented explicitly, which is how `int` hides its `Zero` and `AdditiveIdentity`. 4. Structs and classes can both implement these interfaces; a struct avoids an allocation per intermediate total. ## Choosing the narrowest constraint Every interface in a `where` clause is a demand on every caller. `INumber<T>` is the right constraint for algorithms that genuinely need comparison, parsing and the full set of operators on real numbers. For `Sum`, it would shut out `Money`, units-of-measure structs and vector types for no reason, or force them to fake members. Two traps sit on the other side: - Mixed-type interfaces exist only where the library declares them: `double` implements `IDivisionOperators<double, double, double>` but not `IDivisionOperators<double, int, double>`, so "divide by an `int` count" as a constraint would shut out `double`. - Converting a count into `T` needs `INumberBase<T>.CreateChecked`, which `Money` would not have; a `Mean` for money types usually takes the divisor as a `T` or a `decimal` instead. ## Growing the constraint as the method grows Constraints are easy to add one at a time, and each addition should be driven by a line in the body: - A `Max` helper needs `IComparisonOperators<T, T, bool>`, and `Money` can implement `<` and `>` meaningfully. - A `Scale` helper needs `IMultiplyOperators<T, decimal, T>`, which `Money` can implement without pretending that two amounts multiply. - A helper that needs `T.Parse`, `T.One` and every operator really is numeric, and `INumber<T>` is then honest. The measure of "about sixty" is concrete: an empty `struct M : INumber<M> { }` reports 61 distinct CS0535 errors on the .NET 10 SDK, covering operators, identities, `Abs`, the `Is...` predicates, parsing and formatting. ## What goes wrong - Defining `operator +` without declaring the interface: `Sum<Money>` fails at compile time, because constraints are satisfied by declared interfaces, never by a member with the right name. - Declaring the interface but forgetting a member: CS0535 on the `Money` declaration. - Forgetting `IAdditiveIdentity` while the method uses `T.AdditiveIdentity`: CS0315 at the call, "There is no boxing conversion from 'Money' to 'System.Numerics.IAdditiveIdentity<Money, Money>'."

  • Why does IAdditionOperators take its own implementing type as the first type argument?
    So the operator's signature can name the real type. `static abstract TResult operator +(TSelf left, TOther right)` becomes `Money + Money` for `Money`, with no boxing and no loss of static type. C# also requires an operator declared in an interface to take the containing type or a type parameter constrained to it (CS8924), and the self-referencing constraint on TSelf satisfies that.
  • How would Money support multiplying by a decimal rate in generic code?
    Implement `IMultiplyOperators<Money, decimal, Money>` with `public static Money operator *(Money left, decimal right)`, and constrain the generic method to `where T : IMultiplyOperators<T, decimal, T>`. TOther and TResult exist so operand and result types can differ; no one has to define a meaningless `Money * Money`.
  • What does the compiler report if Money declares IAdditiveIdentity<Money, Money> but omits the property?
    CS0535 on the `Money` declaration: it does not implement interface member `IAdditiveIdentity<Money, Money>.AdditiveIdentity`. Static abstract members are checked exactly like instance interface members, so the error appears where the type is declared, not where `Sum<Money>` is called.

  • Constrain to INumber<T> by default; narrower interfaces are a micro-optimisation.
  • Defining operator + on Money is enough for Sum<T> to accept it.
  • TSelf is just a naming convention and can be any type.
  • Money must be a class to implement static abstract interface members.
  • A missing interface makes Sum<Money> throw at run time.