1

I would like to write a generic sum function on an enumerable of elements that have the + operator implemented.

public T Add<T>(IEnumerable<t> list)=> list.Aggregate((x,y)=>x+y)

I need to say that T implement the + operator with an element of the same type.

with T:IADD<T>

I didn't find if such an interface exists in c#

  • 3
    `Linq` `.Sum()` [system.linq.enumerable.sum](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum?view=net-5.0) – Ryan Wilson May 20 '21 at 13:43
  • [C# interfaces cannot contain operators](https://stackoverflow.com/q/6603940/215552) – Heretic Monkey May 20 '21 at 13:45
  • @RyanWilson I don't think so: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sum?view=net-5.0 .It works with any type only if you give it a function from this type to a number. What I want: I have my own my volume with the + operator. I want to use Add with a list of volume and it returns a volume – Pierre-olivier Gendraud May 20 '21 at 13:48
  • Why not just overload the `+` operator of the `Volume` class then? Why an interface? Both the overloaded operator and the interface would require a class-specific implementation, right? So right now I don't see the advantages of an interface here. – Bart Hofland May 20 '21 at 13:54
  • @RyanWilson Can you flash out your example a bit more? What kind of usage are you trying ideally to achieve in the end? – Nenad May 20 '21 at 14:47
  • 1
    @Nenad I think you tagged the wrong person. I'm not the OP. – Ryan Wilson May 20 '21 at 16:03

1 Answers1

2

No. There is a proposal to add something like this, but (by the location) it is just "under consideration", and has not been earmarked for vNext (C# 10 at time of writing).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900