The params
keyword in C# allows you to specify a method parameter that takes a variable number of arguments. Here are the key points about using params
in C#:
- The
params
keyword must be followed by an array type parameter in the method declaration. The parameter type must be a single-dimensional array. - You can only use the
params
keyword once in a method declaration, and it must be the last parameter in the parameter list. - When calling a method with a
params
parameter, you have several options
You can pass a comma-separated list of arguments of the type specified for theparams
parameter. For example:
void MyMethod(params int[] numbers)
{
// Code implementation
}
// Calling the method with a comma-separated list of arguments
MyMethod(1, 2, 3, 4, 5);
You can pass an array of arguments of the specified type. For example
void MyMethod(params string[] names)
{
// Code implementation
}
// Creating an array and passing it to the method
string[] nameArray = { "John", "Jane", "Alice" };
MyMethod(nameArray);
If you don’t pass any arguments, the length of the params
list will be zero. For example:
void MyMethod(params object[] items)
{
// Code implementation
}
// Calling the method with no arguments
MyMethod(); // The length of the 'items' array will be zero
It’s worth noting that the params
keyword is a syntactic sugar in C#. It simplifies the syntax for passing variable-length argument lists to methods, but behind the scenes, it’s still treated as an array parameter.