Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 830
Semicolon Avatar asked Sep 03 '16 17:09

Semicolon


3 Answers

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);
    }
}
like image 139
Yuval Itzchakov Avatar answered Oct 26 '22 19:10

Yuval Itzchakov


public void Test()
{
    int[]  arr1 = {1};
    int[]  arr2 = {2};
    int[]  arr3 = {3};

    Params(arr1);
    Params(arr1, arr2);
    Params(arr1, arr2, arr3);
}

public void Params(params int[][] arrs)
{

}
like image 20
a-man Avatar answered Oct 26 '22 20:10

a-man


Your method is only set to accept a single array. You could use a List if you wanted to send more than one at a time.

private void myMethod(List<int[]> arrays){
   arrays[0];
   arrays[1];//etc
}
like image 43
Shannon Holsinger Avatar answered Oct 26 '22 20:10

Shannon Holsinger