The ‘params’ keyword in c#
Introduction
I was confused by the appearance of ‘params’ in the signature of a method (see example snippet below). It seemed redundant – even if I removed it, the method worked just fine.
void DisplayStrings(params string[] strings);
Params allows a short-cut during method invocation
While the method itself is unaffected by the ‘params’ in its signature, the caller of the method is affected. The caller can, instead of specifying an array of values, simply pass in a list of values. See the difference in the snippets below.
Normal way of passing in values to this method (using an array)
DisplayStrings(new string[]{"hello","world"})
Params way (shortcut) of passing in values (no array needed, just pass in the values)
DisplayStrings("Hello","World");
Summary
Params just allows a short-cut for passing in an array of values to a method. Instead of initializing and passing an array, one can simply pass in the list of values (comma separated).
Leave a Reply