Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning string[] array into a function with params string[] [closed]

Tags:

I have a function void Test(int id, params string[] strs).

How would I pass an array of strings as the strs argument? When I call:

Test(1, "a, b, c"); 

It takes "strs" as a single string (not an array).

like image 423
Yuen Li Avatar asked Apr 02 '13 06:04

Yuen Li


People also ask

What is params string []?

The params keyword lets you specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

How do you pass a string array to a parameter in Java?

To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);

What is params string in C#?

Params is an important keyword in C#. It is used as a parameter which can take the variable number of arguments. Important Point About Params Keyword : It is useful when programmer don't have any prior knowledge about the number of parameters to be used.


2 Answers

Actually, the params is just a syntactic sugar handled by the C# compiler, so that

this:

void Method(params string[] args) { /**/ } Method("one", "two", "three"); 

becomes this:

void Method(params string[] args) { /**/ } Method(new string[] { "one", "two", "three" }) 
like image 152
illegal-immigrant Avatar answered Oct 22 '22 06:10

illegal-immigrant


I tested this and it works:

    private void CallTestMethod()     {         string [] strings = new string [] {"1", "2", "3"};         Test(1, strings);      }      private void Test(int id, params string[] test)     {         //Do some action with input     } 

You can call it just like this Test(1, <Some string[]>);

Edit

From MSDN website on params:

The params keyword lets you specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

So you could also call the Test method like this Test(1); without compiler errors.

like image 41
jordanhill123 Avatar answered Oct 22 '22 05:10

jordanhill123