I assume you want to write a generic method Sum
like this:
static T Sum<T>(this IEnumerable<T> values) where T : ??
{
T result = 0;
foreach (var value in values)
{
result = result + value;
}
return result;
}
Unfortunately there is no constraint that you could put in place of ??
to make this work.
The data types built into .NET implement certain interfaces. For example, int implements IComparable, IFormattable, IConvertible, IComparable<int>, and IEquatable<int>. None of these provide an Add
method (or +
operator) that would allow you to implement a Sum
method. And you cannot add interface implementation to existing types.
What you can do, is pass a an object to the Sum
method that knows how to add two values of the generic type:
static T Sum<T>(this IEnumerable<T> values, IAdder<T> adder)
{
T result = adder.Zero;
foreach (var value in values)
{
result = adder.Add(result, value);
}
return result;
}
with
interface IAdder<T>
{
T Zero { get; }
T Add(T a, T b);
}
and
class Int32Adder : IAdder<Int32>
{
public static readonly Instance = new Int32Adder();
public int Zero { get { return 0; } }
public int Add(int a, int b) { return a + b; }
}