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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: #511 – Rules for Using Parameter Arrays « 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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: