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.
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
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.
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
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 thanINumber<T>. Fewer demands make your method usable in more places, including your own structs. - Operators are static abstract. Interfaces like
IAdditionOperators<TSelf, TOther, TResult>declarestatic abstract TResult operator +(TSelf, TOther). Implement them on your type as normal operators. - Literals need conversion. You cannot write
T x = 1;. UseT.One, orT.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 is2, not2.33. Convert todoublefirst if you need the fraction. - LINQ.
Enumerable.SumandAveragehave fixed overloads for the built-in types. Generic math lets you write your own versions that also acceptBigInteger,Int128or your own numeric types. - Interfaces on the types. Calling
int.Max(a, b),double.Clamp(...)oruint.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.
Related
num-math,num-clampandnum-parsekw-interfacefor static abstract memberstype-bigint- Tutorial: Generic math and Generic constraints