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

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

  • Comments 10

Update:

Named and optional (default) parameters are available starting from C# 4.0. For more information, see Named and Optional Arguments (C# Programming Guide).

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]

Leave a Comment
  • Please add 4 and 7 and type the answer here:
  • Post
  • 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
  • Would it not be easier to just have an overloaded function?
  • 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.
  • 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.
  • PingBack from http://kohari.org/2006/08/08/misguided-code-part-1/
  • PingBack from http://www.hilpers-esp.com/439417-string-format-dinamico

  • If I have another method as follows,

    public string Concat(params string[] strings)

    and when I call the method Concat("+", "Anders", "Eric", "Scott", "Duncan"), which method will get called?

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

    OR public string Concat(params string[] strings)

    Please clarify.

    Thanks in advance.

  • The code compiles but at runtime code will always pick up "public string Concat(params string[] strings)" method. This actually creates a problem in real time scenario.

  • I don't see where it's elegant. How to create a trace function that takes multiple element and forward to StreamWriter.writeline ?

  • blogs.msdn.com/.../209384.aspx

Page 1 of 1 (10 items)