X

C# tip: use params for method that takes variable number of arguments

dotnet C#

In C# there is a params keyword which allows a method parameter to take variable number of arguments. MSDN

Some notes on param

  • It must always be the last parameter in the function/method definition
  • There can only be one params keyword in a function/method parameter signature

Example:

int Sum(int[] args)
{
  int sum = 0;
  foreach (var item in args)
  {
    sum += item;
  }

  return sum;
}

//calling the above Sum method we would call it like
int[] array = new int[] {1, 2, 3}
int result = Sum(array);

But by changing it to params we can change the call and simplify it

int SumWithParams(params int[] args)
{
  int sum = 0;
  foreach (var item in args)
  {
    sum += item;
  }

  return sum;
}

//calling the above SumWithParams  woud give us the same result
int result = SumWithParams(1, 2, 3);

//calling this would not fail either
int result = SumWithParams(); //result is 0

There is no performance bottleneck in using params because the compiler is basically changing your code into an array for you, thus it is basically just syntactic sugar for C#.

Categories: .NET C#
Taswar Bhatti:
Related Post