Tuesday, 4 June 2013

Variable Arguments (Varargs) in C# and Java

Variable arguments are useful when you do not want to restrict the method usage by setting a definite number of arguments, or simplify implementation of the method if there are many arguments that need to be passed in.


 In C#, params keyword lets you use variable number of arguments. Only one params is permitted for one method, and it must come last. The method would take zero or more arguments into the list, which can be used in the method implementation.

 In Java, '...' is added after the argument type to specify varargs. Otherwise, it is similar to params keyword in C#.

Both example uses for-each loop in the language specific syntax to go through the arguments passed in to the method.

1 comment: