C # params keyword takes 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 provide separate single integers or just one array with several integers . Within the scope of the method, they will be placed in an array called numbers (on the right?), Where can I continue to manipulate them.

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

But if I want to call a method and provide its arrays, I get an error message. How to enable arrays for params ?

 // Results in error var arr = new int[] { 1, 2, 3}; var arr2 = new int[] { 4, 5, 6 }; NumberList(arr, arr2); 
+7
arrays c # params
source share
4 answers

The type you need is int[] . Thus, you either need to pass one int[] , or pass individual int parameters, and let the compiler allocate an array to you. But what your method signature does not allow is multiple arrays.

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

 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); } } 
+6
source share
 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) { } 
+2
source share

Only one array is installed in your method. You can use the List if you want to send more than one at a time.

 private void myMethod(List<int[]> arrays){ arrays[0]; arrays[1];//etc } 
+1
source share

You cannot use langauge. However, there is a way to work around this, crowding out the method as follows:

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

Look here

0
source share

All Articles