How to make an extension method for all integral types?

I wrote a static extension method that acts on int, but I would like to make it more reliable to act on any integral value types , such as ushortor char. Is there any way to do this, with the exception of code duplication?

Right now, my method signature looks something like this:

public static class ExtensionMethods
{
    public static T MyCoolMethod<T>(this int value) where T : struct, IConvertible
    {
        ...
    }
}

Can I exchange intfor some common interface or do something else with generics to get it so that this extension method applies to any integral type?

+4
source share
2 answers

, . , .

+2

, ; , . , , typeof(T).IsPrimitive .

struct, .

+1

Source: https://habr.com/ru/post/1616755/


All Articles