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).
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.
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);
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.
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" })
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.
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