CKTIS / C#
System.Numerics.INumber<T>: static T.Zero and T.CreateChecked
Use `INumber<T>` to write one algorithm for multiple numeric types, get the target type’s zero, and convert values with range checking.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
using System.Numerics;
static T SumAs<T, TSource>(params TSource[] values)
where T : INumber<T>
where TSource : INumberBase<TSource>
{
T sum = T.Zero;
foreach (TSource value in values)
sum += T.CreateChecked<TSource>(value);
return sum;
}INumber<TSelf> in System.Numerics is a contract for comparable numeric types. The constraint where T : INumber<T> requires T to implement the interface with itself as the type argument: for example, int implements INumber<int>. One generic method can then use operators such as + and < on two values of type T without a separate overload for each type.
INumber<T> inherits both static members from INumberBase<T>. T.Zero is a static abstract property that returns zero of type T. Use it to start a sum instead of relying on the literal 0 or assuming default(T) means zero. T.CreateChecked<TOther>(value) is a static virtual method that returns the target type T. The source type TOther must implement INumberBase<TOther> and can usually be inferred from the argument. In generic code, access these members through the constrained type parameter T, not through an instance or the interface name.
For a supported conversion from int to byte, 256 causes OverflowException: CreateSaturating would return 255, and CreateTruncating would return 0. An unsupported type pair can cause NotSupportedException. CreateChecked does not guarantee a lossless conversion; for example, a conversion to float can return infinity rather than throw. The method checks the conversion, not the later += operation.
The generic math interfaces arrived in .NET 7, and static abstract and virtual interface members arrived in C# 11. The example targets C# 12 and .NET 8.
Examples
using System;
using System.Globalization;
using System.Numerics;
Console.WriteLine(SumAs<byte, int>().ToString(CultureInfo.InvariantCulture));
Console.WriteLine(SumAs<byte, int>(40, 2).ToString(CultureInfo.InvariantCulture));
Console.WriteLine(SumAs<int, int>(256).ToString(CultureInfo.InvariantCulture));
try
{
_ = SumAs<byte, int>(256);
}
catch (OverflowException)
{
Console.WriteLine(nameof(OverflowException));
}
static T SumAs<T, TSource>(params TSource[] values)
where T : INumber<T>
where TSource : INumberBase<TSource>
{
T sum = T.Zero;
foreach (TSource value in values)
sum += T.CreateChecked<TSource>(value);
return sum;
}Result
0 42 256 OverflowException
The empty `byte` sum returns `0`; `40` and `2` give `42`. The value `256` fits in `int` but not in `byte`, so the final call prints the name of the caught exception.
Related lessons
- C# · Lesson 5 · Advanced · Version: 3