I do not understand the usefulness of parameter arrays?

Arrays of parameters allow passing a variable number of arguments to a method:

static void Method(params int[] array) {} 

But I do not see their usefulness, since the same result can be achieved by specifying the parameter of a specific type of array:

  static void Method(int[] array) {} 

So, what are the benefits (if any), does the array parameter have the value of the array parameter value?

Thank you

+6
source share
5 answers

The advantage is that the compiler automatically creates an array for you:

 string coor = String.Concat("x=", x, ", y=", y); 

The code created for you is actually:

 string coor = String.Concat(new string [] { "x=", x, ", y=", y }); 

You even get the best of both worlds. If you have data in the array, you can pass it to the params method.

+2
source

This is just code readability. For example, string.Format:

 string value = string.Format("SomeFormatString", param1, param2, param3, param4.... param999); 

It could be written like this in another life:

 string value = string.Format("SomeFormatString", new string[] { param1, param2, param3 }); 

In the end, it's just syntactic sugar to make the code more understandable and understandable.

+7
source

In the second example, the consumer cannot call it with

 MyType.Method(1, 2, 3) 
+6
source

I prefer to write

 Method(1, 2, 3, 4, 5); 

instead

 Method(new int[] { 1, 2, 3, 4, 5} ); 
+2
source

What are their names.

In the first example with parameters, you can call Method(1,2,3,4,5);

In the second example without parameters, you should call it Method(new [] {1,2,3,4,5});

+1
source

Source: https://habr.com/ru/post/887757/


All Articles