0

I want to create the generic method for numeric types. Here is the method:

public static T1 Sum2<T1>(this IEnumerable<T1> values)
{
    return values.Sum();
}

However compiler shows me this error:

error CS1929: 'IEnumerable<T1>' does not contain a definition for 'Sum' and 
the best extension method overload 'Enumerable.Sum(IEnumerable<decimal>)' 
requires a receiver of type 'IEnumerable<decimal>'

Is there a way to solve this error without implementing methods for each numeric type?

Optional Option
  • 1,521
  • 13
  • 33
  • 3
    What happens if I call `Sum2` on a `string` array? – Ron Beyer May 05 '20 at 17:17
  • No. You can also check the frameworks [Enumerable.Sum Method](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum). If there were some elegant way to accomplish this then likely it would have also been done here. – Igor May 05 '20 at 17:21
  • Why you try do this? you already can use linq like this `var result = new List{5,6,2}.Sum();`. If you need sum your own type, you should implement ISummable interface – Denis Stukalov May 05 '20 at 17:25
  • @ron bayer I would be fine with Sum() failing in case of string or any non-numeric type.. – Optional Option May 05 '20 at 17:55
  • By the way the Max() generic method works fine. I do not see why Sum() would be so much different. – Optional Option May 05 '20 at 17:56
  • Since `Sum2` looks to just be a wrapper around `IEnumerable.Sum`, what are you actually trying to do? – Ron Beyer May 05 '20 at 17:58
  • I simplified the method to the bare minimum. I intended to build generic method that does more and uses Sum() but it seems that generic Sum() is just not possible. – Optional Option May 05 '20 at 18:01

0 Answers0