Export (0) Print
Expand All

Using an Indeterminate Number of Parameters (C# vs Java)

C# allows you to send a variable number of parameters to a method by specifying the params keyword when the method is declared. The argument list can contain regular parameters also, but note that the parameter declared with the params keyword must come last. It takes the form of a variable length array, and there can be only one params parameter per method.

When the compiler tries to resolve a method call, it looks for a method whose argument list matches the method called. If no method overload that matches the argument list can be found, but there is a matching version with a params parameter of the appropriate type, then that method will be called, placing the extra arguments in an array.

The following example demonstrates this idea:

class TestParams
{
    private static void Average(string title, params int[] values)
    {
        int sum = 0;
        System.Console.Write("Average of {0} (", title);

        for (int i = 0; i < values.Length; i++)
        {
            sum += values[i];
            System.Console.Write(values[i] + ", ");
        }
        System.Console.WriteLine("): {0}", (float)sum/values.Length);
    }
    static void Main()
    {
        Average ("List One", 5, 10, 15);
        Average ("List Two", 5, 10, 15, 20, 25, 30);
    }
}

In the previous example, the method Average is declared with a params parameter of type integer array, letting you call it with any number of arguments. The output is shown here:

Average of List One (5, 10, 15, ): 10

Average of List Two (5, 10, 15, 20, 25, 30, ): 17.5

You can specify a params parameter of type Object if you want to allow indeterminate parameters of different types.

Community Additions

ADD
Show:
© 2014 Microsoft