#511 – Rules for Using Parameter Arrays

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.

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.

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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #511 – Rules for Using Parameter Arrays

  1. Pingback: #512 – Two Ways to Pass Data to a Method that Takes a Parameter Array « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: