Using Params Keyword

Sometimes we may require a variable number of arguments to be passed to a function. For example we may require a sum function which calculates the total of the numbers passed to it no matter how many numbers are passed.

In C# we can use the Params keyword and pass variable no of arguments to a function. It's much like using ParamArray in VisualBasic language. The syntax of params arguments is:
params datatype[] argument name

Note that the argument passed using params argument should be an singledimension array also it should be the last argument in the argument list for the function.

The params parmeter can then be accessed as an normal array.

Example

class ParamsTest
{
static void Main()
{
System.Console.WriteLine(sum(2,3,4)); // Three Arguments Passed
System.Console.WriteLine(sum(10,20,30,40,50,60));//Six Arguments
}
static int sum(params int[] num)
{
int tot=0;
foreach(int i in num)
{
tot=tot+i;
}
return tot;
}
}

Most Commented Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

One Response to “Using Params Keyword”

  1. More simplied way of doing it:
    class ParamsTest
    {
    static void Main()
    {
    sum(2, 3, 4); // Three Arguments Passed
    sum(10, 20, 30, 40, 50, 60); //Six Arguments

    }
    static void sum(params int[] num)
    {

    foreach (int i in num)
    {
    Console.Write(i);
    Console.ReadLine();
    }

    }