C#
The params keyword
Learn methods that take a variable number of arguments with params.
The params keyword
The params keyword lets a method take a variable number of arguments. The parameter must be of an array type and come last in the list. Declaration: static int Sum(params int[] nums).
At the call site, you can give any number of arguments: Sum(1, 2, 3), Sum(1, 2, 3, 4) or Sum(). The compiler packs the arguments into an array automatically.
params constraints
The params parameter must be the last in the list; it gathers all remaining arguments at the call. A method can have only one params parameter. Its type must be an array, such as int[] or string[].
Inside the body, the params parameter is used like a normal array: you can iterate with foreach (int n in nums) and read its length with nums.Length.
Exercise Sum with params
Define a static int Sum(params int[] nums) method; in the body iterate with foreach (int n in nums), sum all elements and return the result. In Main, call Sum(5, 10, 15) and print the result with Console.WriteLine.
Show example solution
Add foreach (int n in nums) total += n; and return total; to the Sum body, write Console.WriteLine(Sum(5, 10, 15)); in Main.
Example solution:
using System;
class Program
{
static int Sum(params int[] nums)
{
// Sum the items in nums and return
int total = 0;
foreach (int n in nums) total += n;
return total;
}
static void Main()
{
// Call Sum and print
Console.WriteLine(Sum(5, 10, 15));
}
}
Test yourself
-
Match each expression to its meaning
- params int[]
- Variable args
- Sum(1, 2, 3)
- Three args
- Sum()
- Zero args
- params
- Must be last
-
Declare params
static int Sum(____)
{
int total = 0;
foreach (int n in nums) total += n;
return total;
}
Show answer
static int Sum(params int[] nums)
{
int total = 0;
foreach (int n in nums) total += n;
return total;
}
-
What does Sum(1, 2, 3, 4) print?
static int Sum(params int[] nums)
{
int total = 0;
foreach (int n in nums) total += n;
return total;
}
Console.WriteLine(Sum(1, 2, 3, 4));
Show answer
10 — Correct. 1+2+3+4 = 10.
Next lesson: ref parameters