#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");