0

I would like to get the sum of the val field.

// member method 
public T sum()
{
    sum = default(T);
    int i = 0;
    while (i < size)
        sum += val[i++];
}

private int size = 0;
private int usedSize = 0;
private T[] val = null;
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Halimi
  • 121
  • 1
  • 4
  • 1
    is it possible to add more information – sujith karivelil May 05 '16 at 23:02
  • 1
    Trying to do math on values with generic type doesn't work out so well, there are work-arounds but they're all varying degrees of bad. What are you doing with this? Maybe it can be avoided? – harold May 05 '16 at 23:06
  • I want to get the sum of the list, i just switched from c++ to c# – Halimi May 05 '16 at 23:07
  • 2
    You can't do that; The compiler doesn't know that it is possible to add T together. See http://stackoverflow.com/questions/8122611/c-sharp-adding-two-generic-values – flytzen May 05 '16 at 23:08
  • I think you can do that with Linq without needing to implement any function. https://msdn.microsoft.com/en-us/library/system.linq.enumerable.sum(v=vs.110).aspx . Altought it seems you need to pass a parameter, you don't because it is an extension method (notice the **this** word on the parameter). So instead of writing `Sum(Collection)`, you write `Collection.Sum()`. – sergiol May 05 '16 at 23:14
  • You may want to read some C++ vs. C# articles - they are different languages even if both use curly braces. I.e. http://stackoverflow.com/questions/31693/what-are-the-differences-between-generics-in-c-sharp-and-java-and-templates-i should give you some basic differences about generics in C++/C#/Java. – Alexei Levenkov May 05 '16 at 23:44

1 Answers1

1

Here are some worked examples, using System.Linq;

void Main()
{
    List<int> numbers = Enumerable.Range(1,100).ToList();
    var result = numbers.Sum();
    Console.WriteLine(result); // Prints 5050
    List<SomeType> customTypeList = Enumerable.Range(1, 100).Select(x => new SomeType { SomeVal = x}).ToList();
    var customResult = customTypeList.Sum(n => n.SomeVal);
    Console.WriteLine(result); // Prints 5050
}

public class SomeType
{
    public int SomeVal { get; set;}
}
Jonathon Chase
  • 9,396
  • 21
  • 39