Thursday, June 17, 2010

Variable number of arguments

The params keyword is very handy when you don't know the number of arguments is variable.
Note! No additional parameters are permitted after the params keyword.

// This method can take a variable number of ints
public int Sum(params int[] values)
{
  int sum = 0;
  foreach(int value in values)
  {
    sum += value;
  }
  return sum;
}

// Method calls
int sum1 = Sum(1, 2, 3, 4);
int sum2 = Sum(1, 2);

But be aware that this comes with a performance cost. When this method is called an array must be created, which is a costly operation.

If you know that your code for most of the time is calling this method with 3 arguments, then make a override with only three arguments. This method call is much quicker.
// Override with three params
public int Sum(int val1, int val2, int val3) { /* ... */ }
Share:

0 kommentarer:

Post a Comment