You can use the params keyword when declaring a method to define a parameter array, allowing you to pass a variable number of parameters to the method.
1
2
3
4
5
| public void PerformCommands( params string [] commandList) { foreach ( string command in commandList) Console.WriteLine( "Ok, I'm doing [{0}]" , command); } |
You can then pass any number of parameters to the method. Every parameter that you specify is added to the single array that is passed to the method.
1
| kirby.PerformCommands( new string [] { "Sit" , "Stay" , "Come" }); |
When using the params keyword:
- You can only define one parameter array for a given method
- The parameter must be the last parameter specified
- The array must be a single-dimensional array
- You can’t use the ref or out modifiers on the parameter array or on any of the arguments
- Each argument must be implicitly convertible to the type of the array’s elements