ZetCode

C# generic math

last modified November 15, 2026

This article shows how to write generic numeric algorithms in C#. We cover the INumber<T> interface, conversions between numeric types, math functions, binary integer operations, parsing, static abstract interface members, and the operator interfaces.

Before C# 11, a generic method could not add two values of type T: operators are static, and interfaces could only declare instance members. A Sum method had to be written once for int, once for double, once for decimal, and so on. C# 11 introduced static abstract members in interfaces, and .NET 7 used them to build a set of numeric interfaces in the System.Numerics namespace. This is called generic math.

The interfaces are fine-grained. IAdditionOperators<TSelf, TOther, TResult> declares just the + operator, IRootFunctions<T> declares Sqrt and Cbrt, and so on. Composite interfaces combine them: INumber<T> covers the common operators and functions of all numbers, IBinaryInteger<T> adds bit operations for integers, and IFloatingPoint<T> adds rounding for floating-point types. All built-in numeric types implement them.

A generic sum

The first example sums the elements of collections with different numeric types using a single method.

Program.cs
using System.Numerics;

int[] ints = [1, 2, 3, 4, 5];
double[] doubles = [1.5, 2.5, 3.5];
decimal[] prices = [9.99m, 19.99m, 4.50m];

Console.WriteLine(Sum(ints));
Console.WriteLine(Sum(doubles));
Console.WriteLine(Sum(prices));

static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
    T total = T.Zero;

    foreach (var value in values)
    {
        total += value;
    }

    return total;
}

The method works for any type implementing INumber<T>.

static T Sum<T>(IEnumerable<T> values) where T : INumber<T>

The constraint gives the method access to the static members and operators declared in the interface.

T total = T.Zero;

The static Zero property is accessed through the type parameter. We cannot write T total = 0, because the literal 0 is an int.

total += value;

The += operator is available because INumber<T> inherits from IAdditionOperators<T, T, T>.

$ dotnet run
15
7.5
34.48

Converting between numeric types

Generic code often needs to convert values from one numeric type to another. The INumberBase<T> interface provides CreateChecked, which converts any numeric value to T.

Program.cs
using System.Numerics;

Console.WriteLine(Average<int, double>([1, 2, 3, 4]));
Console.WriteLine(Average<byte, decimal>([10, 20, 25]));
Console.WriteLine(Average<double, float>([1.5, 2.25]));

static TResult Average<T, TResult>(T[] values)
    where T : INumber<T>
    where TResult : INumber<TResult>
{
    TResult sum = TResult.Zero;

    foreach (var value in values)
    {
        sum += TResult.CreateChecked(value);
    }

    return sum / TResult.CreateChecked(values.Length);
}

The Average method has two type parameters: the type of the input values and the type of the result.

sum += TResult.CreateChecked(value);

Each value is converted to the result type before it is added. Summing byte values in a byte variable would quickly overflow; summing them as decimal is safe.

return sum / TResult.CreateChecked(values.Length);

The count is converted too, because the division operator requires both operands to be of type TResult.

$ dotnet run
2.5
18.333333333333333333333333333
1.875

Checked, saturating, and truncating conversions

There are three conversion methods. They differ in how they handle values that do not fit into the target type.

Program.cs
int big = 300;
double d = 3.99e10;

Console.WriteLine(byte.CreateSaturating(big));
Console.WriteLine(byte.CreateTruncating(big));

Console.WriteLine(int.CreateSaturating(d));
Console.WriteLine(int.CreateTruncating(-7.9));

try
{
    Console.WriteLine(byte.CreateChecked(big));
}
catch (OverflowException e)
{
    Console.WriteLine(e.Message);
}

The methods can be called on concrete types as well.

Console.WriteLine(byte.CreateSaturating(big));
Console.WriteLine(byte.CreateTruncating(big));

CreateSaturating clamps the value to the range of the target type, so 300 becomes 255. CreateTruncating keeps the low bits, like an unchecked cast; 300 is 0x12C and its low byte is 0x2C, which is 44. For floating-point inputs it truncates the fraction, so -7.9 becomes -7.

Console.WriteLine(byte.CreateChecked(big));

CreateChecked throws an OverflowException when the value is out of range.

$ dotnet run
255
44
2147483647
-7
Arithmetic operation resulted in an overflow.

Math functions

The generic math interfaces also expose the functions known from the Math class as static members.

Program.cs
using System.Numerics;

Console.WriteLine(Hypotenuse(3.0, 4.0));
Console.WriteLine(Hypotenuse(5f, 12f));
Console.WriteLine(Hypotenuse((Half)6, (Half)8));

Console.WriteLine(Mid(1, 10, 5));
Console.WriteLine(Mid(2.5, 0.5, 1.5));
Console.WriteLine(int.Clamp(15, 0, 10));

static T Hypotenuse<T>(T a, T b) where T : IRootFunctions<T> =>
    T.Sqrt(a * a + b * b);

static T Mid<T>(T a, T b, T c) where T : INumber<T> =>
    T.Max(T.Min(a, b), T.Min(T.Max(a, b), c));

We compute the hypotenuse of a right triangle for three floating-point types and the median of three values.

static T Hypotenuse<T>(T a, T b) where T : IRootFunctions<T> =>
    T.Sqrt(a * a + b * b);

The IRootFunctions<T> interface declares the Sqrt method. It is implemented by double, float, Half, and other floating-point types, but not by integers.

static T Mid<T>(T a, T b, T c) where T : INumber<T> =>
    T.Max(T.Min(a, b), T.Min(T.Max(a, b), c));

The Min and Max methods come from INumber<T>. The method returns the middle of the three values.

Console.WriteLine(int.Clamp(15, 0, 10));

Since the members are static members of the numeric types, we can also call them directly, as in int.Clamp or double.Sqrt.

$ dotnet run
5
13
10
5
1.5
10

Binary integers

The IBinaryInteger<T> interface provides bit manipulation methods for all integer types.

Program.cs
using System.Numerics;

Show<byte>(200);
Show(4096);
Show(-1L);
Show(UInt128.MaxValue);

static void Show<T>(T n) where T : IBinaryInteger<T>
{
    Console.WriteLine($"{n}: bits set {T.PopCount(n)}, " +
        $"trailing zeros {T.TrailingZeroCount(n)}, " +
        $"power of two {T.IsPow2(n)}");
}

The Show method prints the number of set bits, the number of trailing zeros, and whether the value is a power of two.

Show<byte>(200);

The literal is converted to byte because we specify the type argument explicitly. The value 200 is 11001000 in binary: three bits set and three trailing zeros.

Show(-1L);
Show(UInt128.MaxValue);

The -1 value of long has all 64 bits set. The same method works for the 128-bit unsigned integer.

$ dotnet run
200: bits set 3, trailing zeros 3, power of two False
4096: bits set 1, trailing zeros 12, power of two True
-1: bits set 64, trailing zeros 0, power of two False
340282366920938463463374607431768211455: bits set 128, trailing zeros 0, power of two False

Generic parsing

The IParsable<T> interface is not limited to numbers. It is implemented by many types that have a Parse method.

Program.cs
var a = Parse<int>("42");
var b = Parse<double>("2.5");
var c = Parse<DateOnly>("2026-11-15");
var d = Parse<Guid>("0f8fad5b-d9cb-469f-a165-70867728950e");

Console.WriteLine(a + 1);
Console.WriteLine(b * 2);
Console.WriteLine(c.DayOfWeek);
Console.WriteLine(d.Version);

static T Parse<T>(string s) where T : IParsable<T> =>
    T.Parse(s, System.Globalization.CultureInfo.InvariantCulture);

A single generic method parses integers, floating-point numbers, dates, and GUIDs.

static T Parse<T>(string s) where T : IParsable<T> =>
    T.Parse(s, System.Globalization.CultureInfo.InvariantCulture);

The Parse method of IParsable<T> takes the string and a format provider. We pass the invariant culture so that the result does not depend on the regional settings of the machine.

$ dotnet run
43
5
Sunday
4

Static abstract members in our interfaces

Static abstract members are a general language feature. We can use them in our own interfaces.

Program.cs
IShape[] shapes = [Circle.Create(1), Square.Create(2)];

foreach (var shape in shapes)
{
    Console.WriteLine($"{shape.Area():F2}");
}

PrintInfo<Circle>();
PrintInfo<Square>();

static void PrintInfo<T>() where T : IShape<T> =>
    Console.WriteLine($"{T.Name} has {T.Corners} corners");

interface IShape
{
    double Area();
}

interface IShape<TSelf> : IShape where TSelf : IShape<TSelf>
{
    static abstract string Name { get; }
    static virtual int Corners => 0;
    static abstract TSelf Create(double size);
}

class Circle(double r) : IShape<Circle>
{
    public static string Name => "circle";
    public static Circle Create(double size) => new(size);
    public double Area() => Math.PI * r * r;
}

class Square(double a) : IShape<Square>
{
    public static string Name => "square";
    public static int Corners => 4;
    public static Square Create(double size) => new(size);
    public double Area() => a * a;
}

The IShape<TSelf> interface declares a static property, a static factory method, and a static virtual property with a default value.

interface IShape<TSelf> : IShape where TSelf : IShape<TSelf>
{
    static abstract string Name { get; }
    static virtual int Corners => 0;
    static abstract TSelf Create(double size);
}

The TSelf type parameter is the implementing type itself; this is the curiously recurring template pattern used by all generic math interfaces. It lets the factory method return the concrete type. Static abstract members can only be accessed through a type parameter, not through an instance. The non-generic IShape base interface allows us to store circles and squares in one array.

static void PrintInfo<T>() where T : IShape<T> =>
    Console.WriteLine($"{T.Name} has {T.Corners} corners");

The method reads the static members without an instance. The Circle class does not implement Corners, so it gets the default value from the interface.

$ dotnet run
3.14
4.00
circle has 0 corners
square has 4 corners

Implementing operator interfaces

Our own types can implement the generic math interfaces and take part in generic algorithms. A method does not need the full INumber<T>; it can require just the interfaces it uses.

Program.cs
using System.Numerics;

Money[] payments = [new(12.50m), new(7.25m), new(30m)];

Console.WriteLine(Sum(payments));
Console.WriteLine(Sum([1, 2, 3]));

static T Sum<T>(IEnumerable<T> values)
    where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>
{
    T total = T.AdditiveIdentity;

    foreach (var value in values)
    {
        total += value;
    }

    return total;
}

readonly record struct Money(decimal Amount)
    : IAdditionOperators<Money, Money, Money>, IAdditiveIdentity<Money, Money>
{
    public static Money AdditiveIdentity => new(0);

    public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);

    public override string ToString() => $"{Amount:F2} EUR";
}

The Sum method requires only addition and an additive identity.

where T : IAdditionOperators<T, T, T>, IAdditiveIdentity<T, T>

The AdditiveIdentity is the value that does not change the result of an addition, zero for numbers.

public static Money AdditiveIdentity => new(0);

public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);

The Money struct implements the two interfaces, so the same Sum method works for it and for int. Implementing INumber<T> for a custom type would mean writing dozens of members; the narrow interfaces keep the requirements small.

$ dotnet run
49.75 EUR
6

Source

Generic math

Tutorial: Explore static virtual members in interfaces

In this article we have written generic numeric code in C#. See also the generics, interface, extension members, and BigInteger tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.