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

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]