Using the params Modifier


C# supports the passing of a variable number of parameters to a method via the modifier params. The params modifier is used to declare an array parameter that is capable of receiving zero or more arguments. When the function is called, the array is loaded from the variable number of parameters and is ready to be accessed by the function code.

A simple example of using a variable number of parameters is shown below.

// Params -- Using the params Modifier

using System;

class Program
{
    static void Main()
    {
        double x = 2.0, y = 3.0, z = 4.0;
        Console.WriteLine("Average of {0}, {1}, {2} is: {3}", x, y, z, Average(x, y, z));

        double[] dArray = { 4.0, 5.0, 6.0 };
        Console.WriteLine("Average of {0}, {1}, {2} is: {3}",
                          dArray[0], dArray[1], dArray[2], Average(dArray));
    }

    static double Average(params double[] array)
    {
        double average = 0;
        for (int i = 0; i < array.Length; i++)
            average += array[i];
        return average / array.Length;
    }
}

The program calculates the average of a varying number of doubles. The output of the program is shown below.

Average of 2, 3, 4 is: 3
Average of 4, 5, 6 is: 5

The first call to Average passes three arguments. These arguments are stored in the array named array. Any number of arguments may be passed. The Length property of the array is used to determine how many arguments were passed on the call.

The second call to Average passes an array of doubles rather than a variable number of parameters. This is quite acceptable.

It is possible for a method to have a number of normal parameters and a single, variable length parameter. The normal parameters must precede the variable length parameter in the parameter list. Only one variable length parameter is possible.