By using the params keyword, you can specify a method parameter that takes a variable number of arguments.You can send a comma-separated list of arguments of the type specified in the parameter declaration or an array of arguments of the specified type. You also can send no arguments. If you send no arguments, the length of the params list is zero.
No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
Example: Write the below code in a console application.
- class Program
- {
- static void Main(string[] args)
- {
- int y = Add(10, 20);
- Console.WriteLine(y);
- Console.ReadLine();
- }
-
- public static int Add(params int[] MyColl)
- {
- int total = 0;
-
- foreach(int i in MyColl)
- {
- total += i;
- }
- return total;
- }
- }
Output
Let us now add few more parameter and see how the result looks like. In the following program I have added three extra arguments.
- class Program
- {
- static void Main(string[] args)
- {
- int y = Add(10, 20, 30, 40, 50);
- Console.WriteLine(y);
- Console.ReadLine();
- }
-
- public static int Add(params int[] MyColl)
- {
- int total = 0;
-
- foreach(int i in MyColl)
- {
- total += i;
- }
- return total;
- }
- }
Following is the output.