The params keyword is used to specify a parameter that takes variable number of arguments. This keyword can be used when you are uncertain about the exact number method parameters.

Things to remember

  • Only one params keyword is allowed in a method declaration.
  • No additional parameters can be specified after the params keyword.
  • The params parameter should be a single dimensional array.

Example

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
Addition(1);
Addition(1, 2);
Addition(1, 2, 3);
Addition(1, 2, 3, 4);
Addition(1, 2, 3, 4, 5);

Console.ReadKey();
}

static void Addition(params int[] numbers)
{
int result = 0;
foreach(int num in numbers)
{
result += num;
}
Console.WriteLine("The sum is {0}", result);
}
}
}

Output

The sum is 1
The sum is 3
The sum is 6
The sum is 10
The sum is 15