what's the difference between that and just creating a method that receives a list or an array?
The difference between
void M(params int[] x)
and
void N(int[] x)
is that M may be called like this:
M(1, 2, 3)
or like this:
M(new int[] { 1, 2, 3 });
but N may only be called in the second way, not the first way.
perhaps it has some impact in performance?
The impact to performance is that whether you call M
in the first way or the second way, either way you get an array created. Creating an array has a performance impact because it takes both time and memory. Remember that performance impacts should be measured against performance goals; it is unlikely that the cost of creating an extra array is the gating factor that is the difference between success and failure in the marketplace.
I don't fully understand or see in what way you would prefer the one with unlimited parameters.
It is purely and entirely a convenience for the author of the code which is calling the method; it is simply shorter and easier to write
M(1, 2, 3);
instead of writing
M(new int[] { 1, 2, 3 });
It just saves a few keystrokes on the caller's side. That is all.
A few questions you did not ask but perhaps would like to know the answer to:
What is this feature called?
Methods that allow a variable number of arguments to be passed on the caller side are called variadic. Params methods are how C# implements variadic methods.
How does overload resolution work with a variadic method?
When faced with an overload resolution problem, C# will consider both the "normal" and "expanded" forms, and the "normal" form always wins if both are applicable. For example, consider this:
void P(params object[] x){}
and we have a call
P(null);
There are two applicable possibilities. In "normal" form, we call P
and pass a null reference for the array. In "expanded" form, we call P(new object[] { null })
. In this case, normal form wins. If we had a call P(null, null)
then normal form is inapplicable and expanded form wins by default.
Challenge: Suppose we have var s = new[] { "hello" };
and a call P(s);
. Describe what happens at the call site and why. You might be surprised!
Challenge: Suppose we have both void P(object x){}
and void P(params object[] x){}
. What does P(null)
do, and why?
Challenge: Suppose we have both void M(string x){}
and void M(params string[] x){}
. What does M(null)
do, and why? How does this differ from the previous case?
params
also requires the type of the argument to be an array. If you need to consume a collection other than an array, it may make more sense to provide a non-params
argument instead.Console.Write
.