Is there a constraint that restricts my generic method to numeric types?

c#, constraints, generics

Solution

This constraint exists in .Net 7.

Check out this .NET Blog post and the actual documentation.

Starting in .NET 7, you can make use of interfaces such as `INumber` and `IFloatingPoint` to create programs such as:

using System.Numerics;

Console.WriteLine(Sum(1, 2, 3, 4, 5));
Console.WriteLine(Sum(10.541, 2.645));
Console.WriteLine(Sum(1.55f, 5, 9.41f, 7));

static T Sum<T>(params T[] numbers) where T : INumber<T>
{
    T result = T.Zero;

    foreach (T item in numbers)
    {
        result += item;
    }

    return result;
}

`INumber` is in the `System.Numerics` namespace.

There are also interfaces such as `IAdditionOperators` and `IComparisonOperators` so you can make use of specific operators generically.

Problem

Can anyone tell me if there is a way with generics to limit a generic type argument `T` to only: - `Int16` - `Int32` - `Int64` - `UInt16` - `UInt32` - `UInt64` I'm aware of the `where` keyword, but can't find an interface for only these types, Something like: ``` static bool IntegerFunction<T>(T value) where T : INumeric ```

Original source

Related problems