Can anyone tell me if there is a way with generics to limit a generic type argument T to only:
Int16Int32
Unfortunately .NET doesn't provide a way to do that natively.
To address this issue I created the OSS library Genumerics which provides most standard numeric operations for the following built-in numeric types and their nullable equivalents with the ability to add support for other numeric types.
sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, and BigInteger
The performance is equivalent to a numeric type specific solution allowing you to create efficient generic numeric algorithms.
Here's an example of the code usage.
public static T Sum(T[] items)
{
T sum = Number.Zero();
foreach (T item in items)
{
sum = Number.Add(sum, item);
}
return sum;
}
public static T SumAlt(T[] items)
{
// implicit conversion to Number
Number sum = Number.Zero();
foreach (T item in items)
{
// operator support
sum += item;
}
// implicit conversion to T
return sum;
}