Reputation: 1765
I'm skimming through Troelsen's Pro C# 2010 and came across the discussion of the params keyword method modifier. Reading the text, MSDN, and other tubez sources, it seems to me the only thing you get from params is the ability to pass a comma delimited list of values to the method. I wrote some code to prove to myself that I can send arrays of different lengths to a method that does not use the params keyword, and everything works just fine.
Now, I'm all in favor of saving keystrokes when it makes sense. In this case, however, I suspect the savings is illusory, and confusing to those who have to maintain code. Illusory because I'm never going to send a hard-coded list of values to a method (bad form!). Confusing because what's a maintainer to make of a method that lists a bunch of values rather than an object that explains what I'm doing?
OTOH, since the most of the folks at MS, and most of the folks here, are smarter than I am, I suspect I'm missing something. Please, anyone, enlighten me!
Thanks.
Upvotes: 5
Views: 564
Reputation: 124632
Because it is easier for me to type:
SomeFuncWithParams(a, b, c);
Than it is to type:
SomeFuncWithParams(new object[] { a, b, c });
And if you think syntactic sugar is not a good reason to implement a feature then you'll also need to start questioning the validity of properties, the using
statement, object initializers, etc.
Upvotes: 3
Reputation: 838066
Have you ever used Console.WriteLine
?
Console.WriteLine("{0}: The value of {1} is {2}.", lineNumber, foo, bar);
This sort of call is where params
can be useful. Having to explicitly construct an array to contain your parameters is just noise which makes the code harder to read without adding any value. Compare to the how it would look if params
weren't used:
Console.WriteLine("{0}: The value of {1} is {2}.", new object[] { lineNumber, foo, bar });
The second version adds no useful information to the code, and moves the values further from the format string, making it harder to see what is going on.
Upvotes: 5
Reputation: 121619
Yes, I've always thought of the .Net "params" keyword as the moral equivalent of C/C++ variadic arguments.
No, I can't think of any way that "params" and a variable-length array aren't completely equivalent.
Upvotes: 1