Use the params keyword to let a method take a variable number of parameters in C#

If you use the keyword params before an array parameter used as the last parameter to 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");
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.