I want to write a generic CumulativeSum
method. Here is the code
public static IEnumerable<T> CumulativeSum<T>(this IEnumerable<T> source) where T : struct
{
T sum = default(T);
foreach (T i in source)
{
sum += i; // Operator '+=' cannot be applied to operands of type 'T' and 'T'
yield return sum;
}
}
As shown in the comment (and as expected), compiler cannot know if a T
can be added to a T
, hence giving error.
One solution is writing an extension method for each and every type I need.
Another solution is replacing T sum = default(T);
with dynamic sum = default(T);
. But this may cause runtime errors (still best way for me).
Is there a keyword for operator overloads which I can use in the conditions like using where T : struct
?