In C#, "params" is a keyword used to create methods that can take a variable number of arguments of the same data type. It allows you to pass a varying number of parameters to a method, making your code more flexible and concise.
Here's how you use the "params" keyword in C#:
public void PrintNumbers(params int[] numbers)
{
foreach (int number in numbers)
{
Console.Write(number + " ");
}
Console.WriteLine();
}
In this example, the method PrintNumbers
takes an array of integers as its parameter, but you can call it with any number of integer arguments:
PrintNumbers(1, 2, 3); // Output: 1 2 3
PrintNumbers(10, 20, 30, 40); // Output: 10 20 30 40
Behind the scenes, the "params" keyword allows you to pass multiple arguments as an array to the method. If you don't provide any arguments, you can still call the method without any parameters:
PrintNumbers(); // Output: (Nothing is printed, as there are no arguments)
Remember that the "params" keyword should be used with the last parameter in the method's parameter list, and a method can have only one "params" parameter.