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[]andList<double>implementIEnumerable<double>, I’d suggest the following: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.