Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Numbers and Math

C# generic math and INumber<T>

Reference for C# generic math: write one method for int, double and decimal using INumber<T>, T.Zero, static abstract members and CreateChecked.

Generic math lets you write a single method that works for any numeric type. It is built on static abstract interface members (C# 11, .NET 7): an interface can declare operators and static methods that each implementing type provides. Every built-in number type (int, long, double, decimal, byte, BigInteger, Int128, Half and more) implements a family of interfaces in System.Numerics, so where T : INumber<T> is enough to use +, -, *, /, comparisons, T.Zero, T.One, T.Abs and more.

Before this feature you had to write an overload per type, or use dynamic. Now the compiler specializes the generic method for each numeric type, so there is no boxing and no performance penalty.

C#
using System.Numerics;

static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
    T total = T.Zero;
    foreach (T v in values) { total += v; }
    return total;
}

Try it

C# One method, many types

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.

C# Constraints, conversions and your own 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.

Syntax

C#
where T : INumber<T>              // + - * / % comparisons, Zero, One, Abs, Max, Min, Clamp, Parse
where T : INumberBase<T>          // the common base; includes CreateChecked and IsNaN/IsZero
where T : IBinaryInteger<T>       // integers: shifts, bit operations, PopCount, DivRem
where T : IFloatingPoint<T>       // Round, Floor, Ceiling, Truncate
where T : IFloatingPointIeee754<T> // NaN, infinities, Sin, Log, Pow, Sqrt, Epsilon
where T : ISignedNumber<T>        // NegativeOne
where T : IUnsignedNumber<T>
where T : IAdditionOperators<T, T, T>   // just +
Member Description
T.Zero, T.One Additive and multiplicative identities (IAdditiveIdentity, IMultiplicativeIdentity).
T.CreateChecked(x) Converts from another number type; throws OverflowException if it does not fit.
T.CreateSaturating(x) Converts and clamps to the target's minimum or maximum.
T.CreateTruncating(x) Converts and keeps the low bits (wraps).
T.Parse, T.TryParse From IParsable<T>, included in INumber<T>.
T.Abs, T.Max, T.Min, T.Clamp, T.Sign Static versions of the Math methods.

Errors: CreateChecked throws OverflowException. Division by zero follows the type: integers throw DivideByZeroException, floating point returns infinity or NaN.

Usage notes

  • Pick the narrowest interface. where T : IAdditionOperators<T, T, T> accepts more types than INumber<T>. Fewer demands make your method usable in more places, including your own structs.
  • Operators are static abstract. Interfaces like IAdditionOperators<TSelf, TOther, TResult> declare static abstract TResult operator +(TSelf, TOther). Implement them on your type as normal operators.
  • Literals need conversion. You cannot write T x = 1;. Use T.One, or T.CreateChecked(1) for other constants.
  • Errors appear at compile time. The constraint rejects non-numbers, so a call such as Sum(new[] { "a" }) fails to build instead of failing at run time.
  • Integer division stays integer. Average(new[] {1, 2, 4}) above is 2, not 2.33. Convert to double first if you need the fraction.
  • LINQ. Enumerable.Sum and Average have fixed overloads for the built-in types. Generic math lets you write your own versions that also accept BigInteger, Int128 or your own numeric types.
  • Interfaces on the types. Calling int.Max(a, b), double.Clamp(...) or uint.PopCount(x) on concrete types uses the same machinery.
  • Performance. For value types the JIT generates one specialized body per type. Reference-type generic arguments are not relevant here, because numbers are structs.