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

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 static string Sum(string separator, paramsint[] numbers)

{

    string result = "";

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

    {

        if (i > 0)

            result += separator;

        result += numbers[i].ToString();

    }

    return result;

}

 

Such a function can be called in two different ways:

 

1)

 

int[] numbers = { 1, 2, 3, 4 };

Console.WriteLine(Sum("+", numbers) + "=" + (int)(1 + 2 + 3 + 4));

 

2)

 

Console.WriteLine(Sum("+", 1, 2, 3, 4) + "=" + (int)(1 + 2 + 3 + 4));

 

 


Posted on Monday, May 12, 2008 by | Comments (1) | Add Comment

Comments

Gravatar

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

Hot damn, looking pertty useful buddy.

Posted on 3/26/2012 8:48:57 PM by Rais #

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

  • Simon Ince's Blog: Hierarchies with HierarchyID in SQL 2008 http://t.co/xSDwiF6rRS.
  • Visual Studio 2010 WAS painfully slow - CodeProject http://t.co/Usba1x6CZy

Valid HTML5