#512 – Two Ways to Pass Data to a Method that Takes a Parameter Array

Defining a parameter array using the params keyword allows you to pass a variable number of arguments to a method.

public void PerformCommands(params string[] commands)

You can pass a variable number of arguments to a method that has a parameter array.

            kirby.PerformCommands("Sit", "Stay", "Beg");

You can also just pass an array of the proper type.

            string[] tricks = new string[] {"Roll over", "Weave"};

            kirby.PerformCommands(tricks);
Advertisements

#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

#340 – Use the params Keyword to Pass a Variable Number of Arguments

When you define a method in a class, the parameters of the method normally dictate the exact number of arguments that you can pass to the method.  There are times, however, when you might want to pass a variable number of parameters to a method.

You could pass a variable number of parameters to a method by using an array.

        public void PerformCommands(string[] commandList)
        {
            foreach (string command in commandList)
                Console.WriteLine("Ok, I'm doing [{0}]", command);
        }

You’d call this method by creating a new instance of an array.

            kirby.PerformCommands(new string[] { "Sit", "Stay", "Come" });

To simplify things, you can use the params keyword in the method definition.  This allows passing the elements of the array as individual arguments.

        public void PerformCommands(params string[] commandList)

This makes calling the method a little cleaner.

            kirby.PerformCommands("Sit", "Stay", "Come", "Fetch");