Title: Use the params keyword in C#
If you use the params keyword before an array parameter used as the last parameter in a method, then the calling code can pass any number of values for that parameter. The following code defines a ShowValues method that can take any number of string parameters.
// Display zero or more values.
private void ShowValues(params string[] values)
{
lstValues.Items.Clear();
foreach (string value in values)
{
lstValues.Items.Add(value);
}
}
The following code shows how the example program calls ShowValues passing it 0, 3, or 5 parameters.
private void btn0_Click(object sender, EventArgs e)
{
ShowValues();
}
private void btn3_Click(object sender, EventArgs e)
{
ShowValues("Red", "Green", "Blue");
}
private void btn5_Click(object sender, EventArgs e)
{
ShowValues("Aardvark", "Bear", "Cantalope", "Dingo", "Eagle");
}
That's all there is to it.
Download the example to experiment with it and to see additional details.
|