Faloude Faloude - 3 months ago 14
C# Question

C# params keyword accepting multiple arrays

Consider this method

public static void NumberList(params int[] numbers)
{
foreach (int list in numbers)
{
Console.WriteLine(list);
}
}


I can call this method and supply seperated single
integers
or just one array with several
integers
. Within the method scope they will be placed into an array called
numbers
(right?) where I can continue to manipulate them.

// Works fine
var arr = new int[] { 1, 2, 3};
NumberList(arr);


But if I want to call the method and supply it arrays instead, I get an error. How do you enable arrays for
params
?

// Results in error
var arr = new int[] { 1, 2, 3};
var arr2 = new int[] { 4, 5, 6 };
NumberList(arr, arr2);

Answer

The type you're requiring is an int[]. So you either need to pass a single int[], or pass in individual int parameters and let the compiler allocate the array for you. But what your method signature doesn't allow is multiple arrays.

If you want to pass multiple arrays, you can require your method to accept any form that allows multiple arrays to be passed:

void Main()
{
    var arr = new[] { 1, 2, 3 };
    NumberList(arr, arr);
}

public static void NumberList(params int[][] numbers)
{
    foreach (var number in numbers.SelectMany(x => x))
    {
        Console.WriteLine(number);
    }
}