Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a real example of when to use params as a method argument?

As I understand it, params is just syntactic sugar that "under the hood" simply gives you an array of the type you specify.

First, when would you use this?

Second, why would you use it instead of just declaring an array argument?

like image 433
richard Avatar asked Apr 28 '11 17:04

richard


People also ask

When should I use params?

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array. No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

Which statement is true about params used as method parameter in C#?

The "params" keyword in C# allows a method to accept a variable number of arguments. C# params works as an array of objects. By using params keyword in a method argument definition, we can pass a number of arguments. Note: There can't be anymore parameters after a params.

What is the difference between method parameter and method argument?

Parameter is the variable in the declaration of the function. Argument is the actual value of this variable that gets passed to the function.

Where do we use params in C#?

In C#, params is a keyword which is used to specify a parameter that takes variable number of arguments. It is useful when we don't know the number of arguments prior. Only one params keyword is allowed and no additional parameter is permitted after params keyword in a function declaration.


1 Answers

Math.Min takes exactly two arguments. This is a stupid limitation. Many other languages allow you to write:

double x, y, z, w;
double least = min(x, y, z, w);

If you wanted to write a min function that could be used like that, you'd want to use params.

like image 176
Ben Voigt Avatar answered Sep 20 '22 21:09

Ben Voigt