Wednesday, September 8, 2010

C#: How to let a method accept a variable number of arguments

The params keyword in C# lets you specify a method parameter that takes a variable number of arguments:


public int AddNumbers(params int[] numbers)
{
 var sum = 0;

 foreach (var number in numbers)
  sum = sum + number;

 return sum;
}

Usage:


var sum1 = AddNumbers(1, 2);
var sum2 = AddNumbers(1,2, 3);
var sum3 = AddNumbers(1,2, 3, 4);
var sum4 = AddNumbers(1,2, 3, 4, 5);