Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 182 ยท Generics

Generic Math and Static Abstract Members

Learn C# generic math (C# 11, .NET 7): INumber of T, operator interfaces, writing Sum once for all numeric types, static abstract members and parsing.

For twenty years, writing a method that adds up numbers meant writing it several times: once for int, once for long, once for double, once for decimal. C# had no way to say "any type that supports +", because operators are static, and interfaces could only describe instance members. Since C# 11 / .NET 7 that gap is closed. Interfaces can declare static abstract members (including operators), and the numeric types implement a rich family of them. The result is generic math: one Sum<T> that works for every numeric type, including ones you define.

This lesson starts from the old pain, introduces the interfaces (INumber<T>, IAdditionOperators<,,> and friends), shows how to write Sum, Average, Clamp and other algorithms once, explains static abstract members so you can build your own, and ends with generic parsing and conversion. It builds directly on generic constraints: generic math is just very powerful interface constraints.

The old problem

Before generic math, code such as this had to be copied per type, or routed through dynamic or object (slow, unsafe):

C# Copy and paste per type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three methods with identical structure. A generic Sum<T> couldn't do total += v, because a plain T has no +, and an interface constraint could not demand one.

Static abstract interface members

The language feature behind it: an interface can declare a member as static abstract, and every implementing type must provide it as a static member. Because the member belongs to the type, not to an instance, generic code can call it through the type parameter: T.Something.

Here is a tiny custom example before the real math interfaces:

C# Your own static abstract members

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice the curiously recurring pattern IShape<TSelf> where TSelf : IShape<TSelf>: the interface knows the implementing type, so Create can return TSelf and not just the interface. Every generic-math interface uses it. Inside Describe<T>, the expression T.Name calls the static member of whatever type T is, and there's no instance, no reflection and no boxing, since the JIT specializes the code per value type.

Operator interfaces

The library splits arithmetic into small interfaces, each with a static abstract operator, so you can ask for exactly what you use:

Interface Provides
IAdditionOperators<TSelf, TOther, TResult> +
ISubtractionOperators<,,>, IMultiplyOperators<,,>, IDivisionOperators<,,> -, *, /
IComparisonOperators<TSelf, TOther, TResult> <, >, <=, >= (plus equality)
IAdditiveIdentity<TSelf, TResult> T.AdditiveIdentity (zero for addition)
IMultiplicativeIdentity<TSelf, TResult> T.MultiplicativeIdentity (one)
IUnaryNegationOperators<,> unary -
INumberBase<TSelf> Zero, One, IsZero, Abs, conversion helpers
INumber<TSelf> all of the above, Min, Max, Clamp, Sign, CopySign

Using the small interfaces, the sum becomes a single method:

C# Sum with fine-grained interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last line demonstrates that byte + byte still follows the type's rules (200 + 100 is 300, which wraps to 44 in an unchecked 8-bit sum). Generic math doesn't change arithmetic, it just lets you write it once. Because the interfaces are so small, hardly anything is left out: INumber<T> bundles them for you.

INumber of T: the practical constraint

In daily work you reach for INumber<T> (declared in System.Numerics). It includes comparison, arithmetic, T.Zero, T.One, and helpers:

C# Sum, Average, Clamp with INumber

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A few points worth stopping on:

  • T.Zero replaces default and the literal 0. A literal 0 is an int, which doesn't convert to a generic T, so you can't write T total = 0;.
  • TResult.CreateChecked(x) converts between numeric types generically. There are three flavors: CreateChecked throws OverflowException when the value doesn't fit, CreateSaturating clamps to the min/max, and CreateTruncating keeps the low bits (like an unchecked cast).
  • Average needs two type parameters, because averaging ints must produce a fractional result. Integer division would hide the fraction ((4 + 5) / 2 is 4). The caller chooses the result type.

If you only need +, ask for IAdditionOperators plus IAdditiveIdentity; if you need many operators, INumber<T> is simpler. More specific families exist: IBinaryInteger<T> (bit operations, shifts, PopCount, LeadingZeroCount), IFloatingPoint<T> and IFloatingPointIeee754<T> (Sqrt, Pow, Sin, Pi, Epsilon), ISignedNumber<T> and IUnsignedNumber<T>, and IMinMaxValue<T> (T.MinValue, T.MaxValue).

More algorithms: powers, GCD, dot product

Constraints you pick depend on the algorithm. Integer algorithms use IBinaryInteger<T>, floating ones IFloatingPoint<T>/IRootFunctions<T>:

C# Algorithms written once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

BigInteger works with Power because it also implements INumber<BigInteger>; so do Half, Int128, nint and any type you write that implements the interfaces. That includes your own numeric types.

A custom numeric type

Because the interfaces are open, you can make your own value type generic-math-ready. To keep it small, implement only the operator interfaces Sum<T> needs (the full INumber<T> has dozens of members):

C# Money that works with Sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same Sum that adds ints adds Money, and the empty-array case returns $0.00 because of AdditiveIdentity. This is the reward: algorithms are written against the abilities of types.

Generic parsing and formatting

The static abstract machinery also covers parsing. IParsable<T> gives T.Parse(string, IFormatProvider?) and T.TryParse; numeric types add ISpanParsable<T> and INumberBase parsing with NumberStyles. That lets you write one "read a list of values" helper:

C# Parsing generically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

int, double, DateOnly, Guid, IPAddress, Version and many more implement IParsable<T>, so the helper needs no switch on type. Your own types can join by implementing static abstract Parse/TryParse from the interface. Passing CultureInfo.InvariantCulture makes the result independent of the machine's regional settings, a good habit for data files.

When to use generic math, and when not

  • Use it for library-style numeric algorithms that must serve many types (statistics, geometry, vectors, matrices), and for code with a specific numeric type in the signature, where a generic variant would remove duplication.
  • Don't use it for ordinary application code: if everything is decimal money, just write decimal. Generic code costs readability; keep the constraints readable (INumber<T> often says enough).
  • Performance: for value types such as int and double, the JIT compiles a separate specialized version of the method, so operations are inlined, and the speed matches hand-written code. For reference types, calls go through a shared version and are slower; numeric types are almost always structs.
  • Remember the numeric traps still apply: overflow wraps in unchecked contexts (byte sum above), float loses precision, and integer division truncates. Pick T carefully and test with edge values.
  • Prefer small interfaces. If an algorithm needs only +, IAdditionOperators plus IAdditiveIdentity documents that and admits more types than INumber<T>.

You can also define static abstract members yourself, as with IShape<TSelf>: factory methods (T.Create), per-type constants (T.Name) and operators are the three typical uses.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why couldn't you write a generic Sum<T> with total += v before C# 11?

    Operators are static, and interfaces could only describe instance members. Static abstract interface members (C# 11) made it possible to constrain T to 'has operator +'.
  2. 2. What is the best way to start a generic sum over INumber<T>?

    A literal 0 is an int that does not convert to a generic T. T.Zero comes from INumberBase<T> and is the additive identity for the actual type.
  3. 3. Which method converts a value to TResult and throws if it does not fit?

    CreateChecked throws OverflowException for values out of range, CreateSaturating clamps to MinValue/MaxValue and CreateTruncating keeps the low bits. A direct cast to a generic type parameter does not compile.
  4. 4. Why does Average<TInput, TResult> need two type parameters?

    Dividing ints truncates. With a separate result type, the total and count are converted to double (or decimal) before dividing.
  5. 5. What does a declaration like interface IShape<TSelf> where TSelf : IShape<TSelf> with static abstract TSelf Create(double size); achieve?

    The self-referencing type parameter lets the interface mention the implementing type, so static members can return it, and generic code can invoke them as T.Create(...).

Summary

  • Generic math (C# 11 / .NET 7) uses static abstract interface members so constraints can require operators and static values such as T.Zero.
  • INumber<T> is the all-round numeric constraint; smaller interfaces (IAdditionOperators, IComparisonOperators, IAdditiveIdentity) request only what an algorithm uses; IBinaryInteger<T> and IFloatingPoint<T> add integer and floating-point features.
  • Write T.Zero, T.One, T.Max, T.Sqrt, and convert with CreateChecked, CreateSaturating or CreateTruncating.
  • All built-in numeric types, BigInteger, Half, Int128 and your own types can take part.
  • IParsable<T> gives generic T.Parse and T.TryParse for numbers, dates, GUIDs and more.
  • Use generic math for reusable numeric code; for simple application code, plain types read better.

Next: Delegates