params

suggest change

params allows a method parameter to receive a variable number of arguments, i.e. zero, one or multiple arguments are allowed for that parameter.

static int AddAll(params int[] numbers)
{
    int total = 0;
    foreach (int number in numbers)
    {
        total += number;
    }
    
    return total;
}

This method can now be called with a typical list of int arguments, or an array of ints.

AddAll(5, 10, 15, 20);                // 50
AddAll(new int[] { 5, 10, 15, 20 });  // 50

params must appear at most once and if used, it must be last in the argument list, even if the succeeding type is different to that of the array.

Be careful when overloading functions when using the params keyword. C# prefers matching more specific overloads before resorting to trying to use overloads with params. For example if you have two methods:

static double Add(params double[] numbers)
{
    Console.WriteLine("Add with array of doubles");
    double total = 0.0;
    foreach (double number in numbers)
    {
        total += number;
    }
    
    return total;
}

static int Add(int a, int b)
{
    Console.WriteLine("Add with 2 ints");
    return a + b;
}

Then the specific 2 argument overload will take precedence before trying the params overload.

Add(2, 3);      //prints "Add with 2 ints"
Add(2, 3.0);    //prints "Add with array of doubles" (doubles are not ints)
Add(2, 3, 4);   //prints "Add with array of doubles" (no 3 argument overload)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Keywords:
* as
* goto
* break
* const
* for
* is
* fixed
* sealed
* typeof
* this
* void
* char
* params
* base
* string
* null
* return
* while
* using
* ulong
* uint
* unsafe
* int
* var
* lock
* where
* extern
* switch
* when
* struct
* static
* do
* bool
* long
* sizeof
* in
* enum
* ushort
* sbyte
* event

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
51 Keywords
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script