Methods That Take Any Number of Values: params
Write a method that takes any number of values with params, and call it with several values, with none, or with an array you already have.
Apprentice · C# · Updated
After this lesson you can
- Write a method that takes any number of values with params
- Call a params method with several values, with none, or with an array
Key takeaways
params decimal[] priceslets a call pass any number ofdecimals, and C# gathers them into the arrayprices.- Inside the method, a params parameter is an ordinary array, with
Length, indexes andforeach. - A params method can be called with several values, with none (the array is then empty), or with an array you already have.
paramsgoes on the last parameter, and a method has only one. Fixed parameters come before it, as inDescribe(string label, params int[] scores).
The snack bar at the ballpark rings up one customer's soda and pretzel, the next customer's soda, pretzel and nachos, and then a family's five things. A method that adds up prices should take however many things the customer bought. You'll want this whenever the number of values changes from one call to the next: the scores of one game or of a whole season, the items on one order, the players on a team.
First try: one method for each count
With the methods you know, each parameter is one value, so a method that adds two prices and a method that adds three are two different methods:
Console.WriteLine(TotalOfTwo(2.50m, 1.75m));
Console.WriteLine(TotalOfThree(2.50m, 1.75m, 3.00m));
decimal TotalOfTwo(decimal first, decimal second)
{
return first + second;
}
decimal TotalOfThree(decimal first, decimal second, decimal third)
{
return first + second + third;
}
4.25
7.25
It works for two things and for three. The family with five needs a TotalOfFive, a party of twelve a TotalOfTwelve, and every new method repeats the same adding with one more parameter. (In the classes chapter you'll see that methods can share one name when their parameters differ, which is called method overloading. That saves names, but it's still one method for each count.)
Second try: make the caller build an array
An array holds any number of values, and a loop adds them up, however many there are. So the method can take an array:
decimal[] order = { 2.50m, 1.75m, 3.00m };
Console.WriteLine(Total(order));
Console.WriteLine(Total(new decimal[] { 4.00m, 1.25m }));
decimal Total(decimal[] prices)
{
decimal total = 0;
foreach (decimal price in prices)
{
total += price;
}
return total;
}
7.25
5.25
One method now handles any count. The catch moves to the code that calls it: every call has to build an array first, even for two prices, and new decimal[] { 4.00m, 1.25m } is a lot to type to say 4.00 and 1.25.
params: the method builds the array for you
Put the word params in front of the array parameter, and the caller can list the values one by one. C# gathers them into an array before the method starts:
Console.WriteLine(Total(2.50m, 1.75m));
Console.WriteLine(Total(2.50m, 1.75m, 3.00m, 4.00m, 1.25m));
decimal Total(params decimal[] prices)
{
decimal total = 0;
foreach (decimal price in prices)
{
total += price;
}
return total;
}
4.25
12.50
- Read
params decimal[] pricesas any number of decimals, gathered into the arrayprices. - Inside the method,
pricesis an ordinary array: it has aLength, its elements have indexes, andforeachvisits each one. Nothing inside the method changed from the second try; only the calls got shorter. - Every value in the call must fit the array's type.
Total(2.50m, "soda")doesn't compile, because"soda"isn't adecimal.
A parameter like this is called a params parameter. In other languages and some textbooks, a method that takes any number of values is called a variadic method.
Three ways to call it
A params method can be called with several values, as above, and in two more ways:
decimal[] lunch = { 6.50m, 2.25m };
Console.WriteLine(Total(4.00m));
Console.WriteLine(Total());
Console.WriteLine(Total(lunch));
decimal Total(params decimal[] prices)
{
decimal total = 0;
foreach (decimal price in prices)
{
total += price;
}
return total;
}
4.00
0
8.75
- One value:
Total(4.00m)gives the method an array of one price. - No values at all:
Total()gives the method an empty array, with aLengthof 0, not a missing one. The loop runs zero times, so the total stays 0. Make sure your method gives a sensible answer for no values. - An array you already have:
Total(lunch)handslunchover as it is, the way the second try did. Code that already has its prices in an array doesn't have to list them again.
The rules: last, and only one
A method can have ordinary parameters as well as a params one. The ordinary ones come first, each with exactly one value, and the params parameter takes everything after them:
Console.WriteLine(Describe("Quiz scores", 90, 85, 77));
Console.WriteLine(Describe("Make-up quiz"));
string Describe(string label, params int[] scores)
{
int best = 0;
foreach (int score in scores)
{
if (score > best)
{
best = score;
}
}
return label + ": " + scores.Length + " scores, best " + best;
}
Quiz scores: 3 scores, best 90
Make-up quiz: 0 scores, best 0
In Describe("Quiz scores", 90, 85, 77), the first value goes to label, and 90, 85 and 77 are gathered into scores. With no scores at all, scores is empty and best stays 0.
C# needs to know where the params values start and stop, so it has two rules:
| Method | Does it compile? |
|---|---|
Describe(string label, params int[] scores) |
Yes: params is the last parameter |
Describe(params int[] scores, string label) |
No: a params parameter must be the last parameter |
Both(params int[] scores, params string[] names) |
No: only one params parameter, and it goes last |
Do it: count the passing scores
The driving school wants to know how many of a class's test scores passed. Sometimes the instructor types the scores in one by one, sometimes the scores are already in an array, and on a day with no tests there are no scores at all.
The method gets two values:
passMark: the lowest score that passes, anint(70).scores: the test scores, any number ofints, gathered into the arrayscoresbyparams(85, 62, 70, 91).
For example, CountPassing(70, 85, 62, 70, 91):
| Score | At least 70? | Passing so far |
|---|---|---|
| (start) | 0 | |
| 85 | Yes | 1 |
| 62 | No | 1 |
| 70 | Yes: exactly the pass mark passes | 2 |
| 91 | Yes | 3 |
So CountPassing(70, 85, 62, 70, 91) returns 3.
Your job: finish the method int CountPassing(int passMark, params int[] scores). Its parameters are written for you: the pass mark first, then the params array.
- Return how many scores are at least
passMark. A score equal topassMarkpasses. - With no scores, as in
CountPassing(70), return0. - It works the same when the scores come in an array: with
int[] quiz = { 90, 75, 50 };,CountPassing(80, quiz)returns1.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
With params, one method handles a call with two values, twenty or none, and the code that calls it reads like a plain list.