Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6956011
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:48:44+00:00 2026-05-27T14:48:44+00:00

Is it possible to template methods for any kind of integer size ? To

  • 0

Is it possible to template methods for any kind of integer size ?

To illustrate, imagine this very trivial example (the body of the method is not important in my question):

public int Mul(int a, int b)    {
    return a*b;
}

Now, I want the same method that supports any kind of integer (excluding BigInteger of course). I have to write all variants :

public long Mul(long a, long b)    {
    return a*b;
}
public ulong Mul(ulong a, ulong b)    {
    return a*b;
}
public short Mul(short a, short b)    {
    return a*b;
}
public ushort Mul(ushort a, ushort b)    {
    return a*b;
}
public byte Mul(byte a, byte b)    {
    return a*b;
}

While this example is very trivial and it’s not actually a problem to duplicate, if I have more complex algorithms like this (replicate for all integer kinds):

    public static IEnumerable<long> GetPrimesFactors(this long number)
    {
        for (long i = 2; i <= number / 2; i++)
        {
            while (number % i == 0)
            {
                yield return i;
                number /= i;
            }
        }
        yield return number;
    }

it introduces a maintenance risk as there is duplicated code and logic (coding integrists would say this is the evil to have same logic at multiple place).

Some of you may suggest to implements the long version and cast the result, but having to ask consumer code to cast can be confusing and reduce readability :

void SomeMethod(IEnumerable<int> valuesToProcess)
{
    foreach(int value in valuesToProcess) { Console.WriteLine(value); }
}

void Main()
{
    int i = 42;
    SomeMethod(((long)i).GetPrimesFactors().Select(l=>(int)l)); 
    SomeMethod(GetPrimesFactors(i));

    long l = 42L;
    SomeMethod(l.GetPrimesFactors().Select(l=>(int)l));
}

When I see the definition of the interface IEnumerable<T>, and especially the definitions of Sum method overloads :

    public static decimal? Sum(this IEnumerable<decimal?> source);
    public static decimal Sum(this IEnumerable<decimal> source);
    public static double? Sum(this IEnumerable<double?> source);
    public static double Sum(this IEnumerable<double> source);
    public static float? Sum(this IEnumerable<float?> source);       
    public static float Sum(this IEnumerable<float> source);
    public static int? Sum(this IEnumerable<int?> source);
    public static int Sum(this IEnumerable<int> source);
    public static long? Sum(this IEnumerable<long?> source);
    public static long Sum(this IEnumerable<long> source);

I conclude that it’s not possible… that’s why MS has to implement all overloads.

Does anyone have any tips for designing general purpose integer methods without having to duplicate logic ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:48:45+00:00Added an answer on May 27, 2026 at 2:48 pm

    There is no clean high performance solution. The choices I can think of are:

    1. Manually duplicate the code (fast and redundant)
    2. Automatically duplicate the code with a code generator (fast but a bit ugly). One .net numerics library went that way, but I don’t remember its name.
    3. Use some form of indirection, such as MiscUtil’s Operator class, or the DLR (slow)
    4. The arithmetic helper struct. I’m not sure how good the performance is, but you can try.

    Generic methods representing operators:

    These were my first idea. The issue is how to implement them. MiscUtil does this by calling a delegate stored in a static field.

    static Func<T,T,T> _multiply;
    public static T Multiply(T n1,T n2)
    {
      return _multiply(n1, n2);
    }
    

    One point to note here, is that you should avoid a static constructor, since its mere existence slows down static field access.

    But that involves an indirect call, and that’s expensive. I next tried to improve this by manually specializing for certain known types:

    public static T Multiply(T n1,T n2)
    {
      if(typeof(T)==typeof(int))
        return (T)(object)((int)(object)n1*(int)(object)n2);
      ...
      return _multiply(n1, n2);
    }
    

    The JIT compiler is smart enough to realize which of those if cases it has to take, and will remove them. While that improved performance, it bloated the IL representation of the methods. And the JIT compiler is not smart enough to inline those method now, since their IL representation is long, and the inline heuristic only looks at the IL length of a method, not its machine code length. I don’t remember if these casts cause boxing, or if the JITter was smart enough to optimize that out. Still the lack of inlining is too costly.

    How 4) works:

    First create an interface that contains the basic operations you need(arithmetic operators,…):

    interface IArithmetic<T>
    {
       T Multiply(T n1,T n2);
    }
    

    Implement it for each type you need with a struct:

    public struct Int32Arithmetic:IArithmetic<Int32>
    {
       Int32 Multiply(Int32 n1,Int32 n2)
       {
         return n1*n2;
       }
    }
    

    Then make most of your actual code generic, and pass in an arithmetic helper:

    internal T MyOperation<T,TArithmetic>(T n1, T n2)
      where TArithmetic:struct,IArithmetic<T>
    {
       return default(TArithmetic).Multiply(n1,n2);
    }
    

    And if you want a clean interface for multiple types, create a thin overloaded wrapper forwarding to the generic method:

    public Int32 MyOperation(Int32 n1,Int32 n2)
    {
      return MyOperation<Int32,Int32Arithmetic>(n1, n2);
    }
    

    This might be fast, because generics get specialized for each value type. It uses no indirections and the method bodies in IL don’t get too long, so inlining is possible. But I haven’t tried this myself yet.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is one of the possible ways I come out: struct RetrieveKey { template
I wonder if it is in any way possible to specialize generic interface methods
Is it possible to do template layouts which you can assign to all your
Possible Duplicate: C++ HTML template framework, templatizing library, HTML generator library Planning to write
Is it possible to write a template that changes behavior depending on if a
Is it possible to use a data template for a single item with no
Is it possible to extend a base template with another template in Smarty? I
Is it possible to create a template function that takes a variable number of
Is it possible to use the using declaration with template base classes? I have
Is it possible to create a Visual Studio item template that generates from a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.