C# params keyword
January 25th, 2008
Lets take a look at what the params keyword does.
It mainly gives you the ability to create functions that take a variable number of arguments - often called “variadic” or “variable arity” functions. This is not a really new feature only provided by C# you can also find it in C and C++, in the form of the “…” syntax, and Java uses that syntax as well. (e.g. Exception{} catch(…))
I’d like to show how useful the usage in C# can be:
public int Sum(params int[] list) { int res = 0; foreach (int i in list) res += i; return res; }
As you can see, the params keyword is used as an argument list for a number of typed vars.
You can call that small function with zero or more arguments.
int result = Sum(5); result = Sum(5,4,3,4); result = Sum(new int[] { 3,4,4,2,11 }); result = Sum();
This would report an error because the arguments are invalid:
int result = Sum(1,2,3 new int[] { 4,5,6 });
Even though you can pass in lists/array for the params, you can’t mix it up with regular values at all.





