C#

C# params

C# params allows you to design a method which accepts variable number of parameters. These parameters are stored in an array and available to called method.


static void DoWork(params int[] arr)
{
    if (arr != null)
    {
        foreach (var i in arr)
        {
            Console.WriteLine(i);
        }
    }
}

There are two ways to send parameters using params keyword:

  1. You can fill all parameters in an array and pass the array as a parameter in a method.
  2. You can provide parameters using comma-separated list when calling a method.

Array as parameters

Below is the example of passing array as parameter in a params method.


static void Main(string[] args)
{
    int[] arr = { 1, 2, 3 };
    DoWork(arr);
}

static void DoWork(params int[] arr)
{
   ...
}

We have declared an array arr and initialized it with three array items 1,2,3. In the second line of Main method, we pass the arr as parameter in DoWork method. DoWork method has a paramter using params array arr. All the array items are filled in the DoWork arr parameter.

Comma-seperated list parameters

Below is the example of comma-separated list parameters.


static void Main(string[] args)
{
    DoWork(1, 2, 3, 4);
}

static void DoWork(params int[] arr)
{
}

In the above example, we have not declared any array. We pass the arguments 1,2,3,4 directly in the calling method statement.

C# Params constraints

There is a constraint of using params keyword in method parameters. params can only be used with last parameter of the method. For example:

static void DoWork(params int[] arr) { }
static void DoWork(int par1, params int[] arr) { }
static void DoWork(int par1, string par2, params int[] arr) { }

All the above overloaded method will compile successfully. As params keyword is used with the last parameter.

Below examples are failed to compile:


static void DoWork(params int[] arr, int par1) { }
static void DoWork(params int[] arr, int par1, int par2) { }

For the above examples, C# compiler will issue this error “A parameter array must be the last parameter in a formal parameter list”.

When to use params

params parameter keyword is useful when we don’t know in advance how many parameters we are expecting. You can use params keyword with only single type of parameter. If you want to work with multiple types, you should use params with object array like shown below:

static void Main(string[] args)
{
    DoWork(1, "First Name", 3, "Second Name", new CustomClass());
}

static void DoWork(params object[] arr)
{
    if (arr != null)
    {
        foreach (var i in arr)
        {
            Console.WriteLine(i);
        }
    }
}