Params Arrays:
Sometimes, we are not assured about the member of Parameters or we want to create a Method that can accept a Number of Parameters at Runtime. C# Param Arrays (Or Parameter Arrays) come to help in such situation. The Params Keyword create an Array at Runtime that receives and holds "N" number of Parameters.
Params keyword in C# allows a method or a constructor to receive a variable number of parameters. When params are used then the compiler converts the arguments passed to a method into a temporary array. This temporary array than can be used in the receiving method to perform some operation on its elements. When using params you can pass a comma-separated list of arguments of the type specified in the method signature or an array of arguments of the specified type. It also gives us the flexibility to send no arguments to the method and in such a case the length of the params list is zero.
Syntax of Params Parameter:
By Using the Params keyword, we can specify a Method parameter that takes a Variable Number of Arguments using this Syntax:
Access-Specifier Data-Type Variable-name( paramsint[] Variable-name )
{
//Body:
}
Example:
Let's have an simple example to know how we can declare and use Params Arrays.in this example, we will create a Method add() using Params keyword, that will receives any number of Integer parameters at run time and Returns the Sum of all Those Numbers.
/*Example: Params Array: InfoBrother:*/
using System;
namespace paramsArray
{
class Program
{
static int add(params int[] numbers)
{
int sum = 0;
foreach (int n in numbers)
{
sum = sum + n;
}
return sum;
}
//main method:
static void Main(string[] args)
{
int sum;
// passing 05 parameters
sum = Program.add(1, 2, 3, 4, 5);
Console.WriteLine("Sum of 1,2,3,4,5 is:\t{0}", sum);
// passing 07 parameters
sum = Program.add(10, 20, 30, 40, 50, 60, 70);
Console.WriteLine("Sum of 10,20,30,40,50,60,70 is:\t{0}", sum);
Console.ReadLine();
}
}
}
Params Arrays:
Sum of 1,2,3,4,5 is: 15
Sum of 10,20,30,40,50,60,70 is: 280