KARPACH

WEB DEVELOPER BLOG

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:

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

Console.WriteLine(Sum("+", numbers) + "=" + (int)(1 + 2 + 3 + 4));
Console.WriteLine(Sum("+", 1, 2, 3, 4) + "=" + (int)(1 + 2 + 3 + 4));
Posted on May 12, 2008 by

Comments

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

Hot damn, looking pertty useful buddy.