HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constraintnumericmethodrestrictsthatgenerictypesthere

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 value) where T : INumeric

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(params T[] numbers) where T : INumber
{
    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.

Code Snippets

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;
}

Context

Stack Overflow Q#32664, score: 22

Revisions (0)

No revisions yet.