I was supposed to write a method, which will perform addition on collection of integer, float or double. I was going to write a three methods which will traverse three different types perform addition and return the value. It works. I am just curious, Is this can be done in a single method, where the type is passed a a generic type, something like
public static T SUM<T>(IEnumerable<T> dataCollection)
{
T total;
foreach(var value in dataCollection)
total += value;
return total;
}
I was able to resolve it with normal three method implementation but just curious, is it even possible?
Thanks,
It’s not possible to use operators like
+ / - / * / etc ...on expressions which are typed to generic type parameters. These only work when dealing with concrete types.To do this with generics you’ll need to pass in an abstraction which understands how to do operations like
+on the actual type ofT. For example, here’s a lambda exampleNote: As several have pointed out the function I wrote here is essentially identical to
System.Linq.Enumerable.Aggregate. Please use that vs. putting this in your code.