0

I want to create an extension method for IEnumerable that calculates the sum of its terms and returns the total value. This method must perform this sum only if type T is a numeric type (double, float, int ...) and this sum must be different if the IEnumerable is a list, a set, or a dictionary.

My attempt to create this method is just below:

public static class IEnumerableTExtensoes
{
   public static double Sum<T>(this IEnumerable<T> IEnum)
    {
        bool isInt = typeof(T) == typeof(int);
        bool isFloat = typeof(T) == typeof(float);
        bool isDouble = typeof(T) == typeof(double);

        if(isInt || isFloat || isDouble)
        {
            T sum = (double)0;
            foreach(T num in IEnum)
            {
                sum += num;
            }
        }
        return sum;
    }
}

That is not working at all.

Any suggestion?

1 Answers1

1

Let me guess: this is not working because T does not define operator +.

There are two ways that I can think of that you could use to solve this, but I cannot test either one of them, so I cannot vouch as to whether each one of them will work, or whether it will turn out to be impossible due to some detail that I am missing right now.

One way would be to declare 3 separate methods:

public static double Sum(this IEnumerable<Int32> ienum),

public static double Sum(this IEnumerable<Float> ienum), and

public static double Sum(this IEnumerable<Double> ienum).

Another way would be to take advantage of the fact that all 3 types of interest implement the IConvertible interface. So, you would declare your Sum<T>() method with where T: IConvertible then within the loop you would convert each value to a known common denominator, say to Double, so that you can perform the summation, and then finally you would (somehow, I am not sure, perhaps with a cast?) convert it back to type T so you can return it.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • 1
    Worth noting that `System.Linq.Enumerable` uses the many-overloads approach, not just for `Sum` but also `Min`, `Max`, and `Average` – Ben Voigt May 22 '17 at 19:41