9

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);

4 Answers 4

7

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3
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)
{

}

Comments

0

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
}

Comments

0

You cant by langauge means. However there is a way to work arround this by overlading the method something like this:

public static void NumberList(params int[][] arrays)
{
    foreach(var array in arrays)
        NumberList(array);
}

See here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.