3

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,

0

1 Answer 1

6

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 of T. For example, here's a lambda example

public static T SUM<T>(IEnumerable<T> dataCollection, Func<T, T, T> sum)
{
  T total = default(T);
  foreach(var value in dataCollection)
    total = sum(total, value);
  return total;
}

List<int> list = ...;
list.Sum((left, right) -> left + right);

Note: 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.

Sign up to request clarification or add additional context in comments.

4 Comments

Of course, that's little more than a roll-your-own Aggregate() function, as the lambda passed could be anything from left - right to left / right.
@Nair, note that exactly this function is already there Enumerable.Aggregate, please try to use it instead unless you doing it to learn something.
Yes it is part of learning experience then again, I did not know about Aggregate as well.
@JaredPar in the above method as it is, sum(total, value) compiler compains about total not assigned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.