Reputation: 4423
I'm just curious, what is considered the "best practice" for the following example: I have either a numeric array or numeric list and want to supply it to a function to return the average.
Is it better to overload the method for each case:
double Average(int[] intArray){...}
double Average(uint[] uintArray){...}
double Average(double[] doubleArray){...}
...
double Average(List<int> intList){...}
...
Or, is it better to use some type of interface:
double Average(IEnumerable arrayOrList)
{
// Branching logic for array or list.
}
Thanks!
EDIT
Average
is used as an example. I have several numeric algorithms which need to be able to run on a variety of numeric data.
Upvotes: 1
Views: 369
Reputation: 217263
Take a look at the various overloads of the Enumerable.Average Extension Method for guidance:
public static double Average(this IEnumerable<int> source)
A method in this style works for any collection type that implements IEnumerable<T> (T[], List<T>, HashSet<T>, ReadOnlyCollection<T>, ...) and avoids the overhead incurred by a non-generic IEnumerable argument. Since C# doesn't have a where T : num
constraint, you need to provide an overload for all primitive types you wish to support (Int32, Int64, Single, Double, Decimal, ...).
Upvotes: 3
Reputation: 1893
Assuming Average
is just an example, you should use IEnumerable but overload the funciton with your data type, like so: IEnumerable<DataType>
For example:
double Average(IEnumerable<Int32> array){...}
double Average(IEnumerable<Double> array){...}
Upvotes: 0
Reputation: 10307
An interface will allow you to supply an array or any other collection. You might want to use a strongly typed interface like IEnumerable<int>
though.
Upvotes: 1