C# Frequently Asked Questions

The C# team posts answers to common questions

How do I write a method that accepts a variable number of parameters?

Q: How do I write a method that accepts a variable number of parameters?

 

A: Languages like C and C++ have always offered some means for using and creating functions capable to accept a variable number of parameters. The most widely known example of a function which takes a variable number of parameters is printf():

 

      int printf(char *format, …);  // the ellipsis means "variable number of params"

 

Using this function is pretty easy:

 

      printf("Hello, world\n");

      printf("The sum of %d and %d is %d\n", a, b, a+b);

 

However, the creation of such functions in these languages relays on a set of predefined macros and is not particularly elegant or intuitive.

 

C# offers an elegant solution to this problem through parameter arrays. A parameter array is a single-dimensional array included as the last parameter in the parameter list of a method:

 

            public string Concat(string separator, params string[] strings)

            {

                  string result = "";

                  for (int i = 0; i < strings.Length; i++)

                  {

                        if (i > 0)

                             result += separator;

                        result += strings[i];

                  }    

                  return result;

            }

 

Such a function can be called in two different ways:

 

a)      Passing the function an array instance argument:

 

                  string[] names = { "Anders", "Eric", "Scott", "Duncan" };

                  MessageBox.Show(Concat("+", names) + " = great team");

 

b)      Using zero or more type-compatible arguments for the parameter array:

 

                  MessageBox.Show(Concat("+", "Anders", "Eric", "Scott", "Duncan") +

" = great team");

 

In this case, the invocation will create an array from the supplied arguments and use it as the actual argument.

 

Thanks to the unified .NET type system, object[] can be used as “common denominator” for arguments of different types:

 

            public int SumTheIntegers(params object[] list)

            {

                  // sum all the integers included in list

int sum = 0;

                  foreach (object o in list)

                        if (o.GetType() == typeof(int))

                             sum += (int) o;

                  return sum;

            }

 

[Author: Octavio "Dave" Hernandez]

Published Thursday, May 13, 2004 3:44 PM by CSharpFAQ

Comments

 

DotWind Solutions said:

Very interesting, I used to do it with the object[] but not with the params

I added it to my blog
http://blog.dotwind.com/archive/2004/05/13/162.aspx
May 13, 2004 5:14 PM
 

Julius L. S. Penn said:

Would it not be easier to just have an overloaded function?
May 18, 2004 8:33 AM
 

Octavio Hernandez said:

Would it not be easier to just have an overloaded function?

A. For the very simple case when you want to accept 0 or 1 parameters, yes. But as the possible amount of [optional] parameters grow, it becomes more and more impractical to have n overloads. And of course the general case can be only covered using an approach such as C#'s.
May 26, 2004 4:39 AM
 

C Rule said:

I am trying to pass a listbox's SelectedItems - but am getting an error when I try to cast the object into a DataRowView during the foreach statement - I need to do that or all it captures is System.DataRowView.View.....
Can you help?

This is my code:

MessageBox.Show("" + GetCars(", ", listBox1.SelectedItems));

public string GetCars(string separator, params object[] drv)
{
string selected = "";
int count = 0;
foreach(DataRowView x in drv)//here is the casting error
{
if(count >= 0)
{
selected += separator;
}
selected = (x["CarID"].ToString());
count ++;
}
}
return selected;
}

Thanks for your help.
May 27, 2004 1:16 PM
 

Misguided Code, Part 1 at Nate Kohari said:

August 8, 2006 3:09 PM
 

string.Format Din?mico | hilpers said:

January 20, 2009 2:54 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker