Search code examples
c#genericsmethodstype-constraints

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!


Solution

  • 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.