CKTIS / C#
INumber<T>: generic numeric calculations
INumber<T> lets you write one generic method for different numeric types. Its constraint exposes operators and the inherited T.Zero and T.CreateChecked members, allowing you to initialize an accumulator and convert input values.
Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification
Syntax
static T SumAs<T>(int[] values) where T : INumber<T>
{
T total = T.Zero;
foreach (int value in values)
total += T.CreateChecked(value);
return total;
}INumber<T> in System.Numerics is a generic math interface. The constraint where T : INumber<T> means that T implements this interface for itself. It exposes arithmetic and comparisons, letting one method support types such as int and decimal. The interface was introduced in .NET 7; accessing static interface members through a type parameter requires C# 11 or later. In a net10.0 project with LangVersion=preview, this example needs no preview features.
INumberBase<T>.Zero is an inherited static abstract property that returns zero of type T; use T.Zero inside a generic method. INumberBase<T>.CreateChecked is an inherited static virtual method, called as T.CreateChecked(value). Its source type parameter satisfies where TOther : INumberBase<TOther>. Converting a value outside the destination type’s range can throw OverflowException, but it does not always do so. For example, Half.CreateChecked(100000) returns positive infinity instead of throwing. An unsupported source type can cause NotSupportedException.
The example sums int values after converting each one to T. An empty array yields T.Zero. The name CreateChecked applies to conversion: it does not automatically enable overflow checking for subsequent addition. The constraint also does not standardize arithmetic semantics across types—for example, int division remains integer division.
Examples
using System;
using System.Globalization;
using System.Numerics;
int[] values = { 2, 3, 5 };
Console.WriteLine(SumAs<int>(values));
Console.WriteLine(SumAs<decimal>(values).ToString(CultureInfo.InvariantCulture));
static T SumAs<T>(int[] values) where T : INumber<T>
{
T total = T.Zero;
foreach (int value in values)
total += T.CreateChecked(value);
return total;
}
Result
10 10
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.