Microsoft & .NETVisual C#.NET Tip: Passing a Variable Number of Arguments to a Method

.NET Tip: Passing a Variable Number of Arguments to a Method

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

If you need to pass an unknown number of arguments to a method, the params keyword is exactly what you need. With params, you can pass a variable number of parameters to a method and any parameters after the fixed parameters will be collected into an array and passed to your method. You can only use the params keyword for one parameter in your method declaration and it must always be the last parameter. A method that accepts a string and then a variable number of parameters of any type looks like this:

public void ObjectParams(string Message, params object[] p)
{
   Console.WriteLine(Message);
   for (int i = 0; i < p.Length; i++)
   {
      Console.WriteLine(p[i]);
   }
}

This method prints the string parameter to the console then loops through variable parameters, printing each one to the console as well. It accepts an array of objects, so the parameters can be any data type. You would call the function like this:

ObjectParams("Variable Object Parameters", 12, 'z', "Test");

If you know the data type of your arguments, you can optimize this somewhat by specifying a type other than object for the variable parameters. A method that expects a variable number of integers would look like this:

public void IntParams(string Message, params int[] p)
{
   Console.WriteLine(Message);
   for (int i = 0; i < p.Length; i++)
   {
      Console.WriteLine(p[i]);
   }
}

You call this method the same way as before, only passing integers.

IntParams("Variable Integer Parameters", 1, 2, 3, 4, 5);

You also can pass an array as the last parameter instead of passing individual parameters. The previous method, which accepts integers, also could be called this way.

int[] TestIntArray = new int[5] { 11, 12, 13, 14, 15 };
IntParams("Integer Array Parameter", TestIntArray);

The ability for a method to accept a variable number of parameters can come in handy in many situations. Now, with the params keyword, you have what you need to take advantage of this ability in C#.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories