Wednesday, March 18, 2009

Params Modifier

In some cases you might need a function which takes an arbitrary number of parameters.This
could of course be done by accepting an array or a list as a parameter, like this:
static void GreetPersons(string[] names) { }
However, calling it would be a bit clumsy.
In the shortest form, it would look like this: GreetPersons(new string[] { "John", "Jane", "Tarzan" });
It is acceptable, but it can be done even smarter, with the params keyword:
static void GreetPersons(params string[] names) { }
Calling it would then look like this:
GreetPersons("John", "Jane", "Tarzan");
Functions with params can even take other parameters as well, as long as the parameter with the params keyword are the last one. Besides that, only one parameter using the params keyword can be used per function.

No comments:

Post a Comment