Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic Type Constraints

I have never used generics before and was wondering how to constrain the Type to either Double[] or List<Double> (or if this is even the correct thing to do). I need to calculate the average of many numbers that are sometimes known in advance (i.e. I can create an array of exact size) but, at other times, are generated immediately before the calculation (i.e. I use a List).

I would like this generic method Average(T arrayOrList) to be able to accept an array or list instead of overloading the Average() method.

Thanks!

like image 393
john Avatar asked Aug 31 '26 23:08

john


2 Answers

Since both double[] and List<double> implement IEnumerable<double>, I'd suggest the following:

public double Average(IEnumerable<double> arrayOrList) {
    // use foreach to loop through arrayOrList and calculate the average
}

That's simple subtype polymorphism, no generics required.

As others have already mentioned, if you simply want to calculate an average, such a method already exists in the framework.

like image 185
Heinzi Avatar answered Sep 03 '26 16:09

Heinzi


I would just use IEnumerable<double>, since all you need to do is loop over the data (and both lists and arrays support this, as do deferred sequences).

In fact, Microsoft got there first:

var avg = sequence.Average();

http://msdn.microsoft.com/en-us/library/bb358946.aspx

like image 28
Marc Gravell Avatar answered Sep 03 '26 16:09

Marc Gravell