Parameter Arrays
C# enables you to specify one (and only one) special parameter for a function. This parameter, which must be the last parameter in the function definition, is known as a parameter array . Parameter arrays enable you to call functions using a variable amount of parameters and are defined using the params keyword.
Parameter arrays can be a useful way to simplify your code because you don ’ t have to pass arrays from your calling code. Instead, you pass several parameters of the same type, which are placed in an array you can use from within your function. The following code is required to define a function that uses a parameter array:
static < returnType > < functionName > ( < p1Type > < p1Name > , … ,
params < type > [] < name > )
{
…
return < returnValue > ;
}
You can call this function using code like the following:
< functionName > ( < p1 > , … , < val1 > , < val2 > , …)
Here < val1 > , < val2 > , and so on are values of type < type > , which are used to initialize the < name > array. The number of parameters that you can specify here is almost limitless; the only restriction is that they must all be of type < type > . You can even specify no parameters at all.
This final point makes parameter arrays particularly useful for specifying additional information for functions to use in their processing. For example, suppose you have a function called GetWord() that takes a string value as its first parameter and returns the first word in the string:
string firstWord = GetWord(“This is a sentence.”);
Here, firstWord will be assigned the string This . You might add a params parameter to GetWord() , enabling you to optionally select an alternative word to return by its index:
string firstWord = GetWord(“This is a sentence.”, 2);
Assuming that you start counting at 1 for the first word, this would result in firstWord being assigned the string is . You might also add the capability to limit the number of characters returned in a third parameter, also accessible through the params parameter:
string firstWord = GetWord("This is a sentence.", 4, 3);
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static int SumVals(params int[] vals) { int sum = 0; foreach (int val in vals) { sum += val; } return sum; } static void Main(string[] args) { int sum = SumVals(1, 5, 2, 9, 8); Console.WriteLine("Summed Values = {0}", sum); Console.ReadKey(); } } }