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);
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);
}
}
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)
{
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With