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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With