Search code examples
c#variadic-functionsdesign-decisionsvariadic

What was the design decision for variadic functions needing an array?


I am curious and hopefully someone can shed somelight on this - but why do the C# functions that take 'params' have to be an array?

I get that the objects in the parameters list are entered into an array but what if someone wants to create a variadic function that takes in an undefined number of array objects?

Take this function for example...

private Int32 Sum(params Int32[] numbers)
{
    return numbers.Sum(); // Using LINQ here to sum
}

Pretty straight forward, it can take in a different amount of numbers - for example...

Int32 x = Sum(1);
Int32 y = Sum(1, 2);
Int32 z = Sum(1, 2, 3);

Now lets say I want to create a function that takes in a different amount of Integer arrays and sums up all the numbers. As far as I am aware I would have to consider boxing...

private Int32 SumArrays(params Object[] numbers)
{
    Int32 total = 0;
    foreach (Object o in numbers)
    {
        Int32[] array = (Int32[])o;

        total += array.Sum();
    }
    return total;
}

Which could then be used like...

Int32[] arr1 = new Int32[] { 1, 2, 3 };
Int32[] arr2 = new Int32[] { 1, 2, 3, 4 };
Int32[] arr3 = new Int32[] { 1, 2, 3, 4, 5 };

Int32 x = SumArrays((Object)arr1, (Object)arr2);
Int32 y = SumArrays((Object)arr1, (Object)arr2, (Object)arr3);

What was the reasoning behind this? Why wasn't this ever implemented as just a single non array variable? Such as params Int32?


Solution

  • The functionality is already there, no need to resort to boxing:

    private int SumAll(params int[][] args)
    {
        int result = 0;
        for (int x = 0; x < args.Length; x++)
        {
            for (int y = 0; y < args[x].Length; y++)
            {
                result += args[x][y];
            }
        }
        return result;
    }
    

    You just need to add it an array of arrays.