Params in C# - easy to use tutorial

2:59 PM

There is interesting concept in C# - params. Here is the refference in MSDN
Lets assume you want do create method that should add numbers and return a result.
In our regular way we can build it as following:

private int sumAllNumbers(int num2)
{
  int sum = sumAllNumber(1, 2);
  return sum;
}
Such approach has some limits and not flexibale enough, because in this case we limited to add only two numbers. So our logical way to improve it may look like this :
private sumAllNumbers(int[] numbers)
{
   int sum = 0;

   foreach(int num in numbers)
   {
     sum += num;
   }
   return sum;
}

This is better attitude but in this case in order to use this method we should create an instance of array of integers. This mean that we should know size of that array in compile time. Another problem in this case : before sending this array to sumAllNumbers method we should check if our array of integers hold propper informations ( we should avoid nulls and such).

In order to make sumAllNumbers  method to more flexibale we can use params.


private int sumAllNumber(params int[] numbers)
{
  int sum = 0;

  foreach(var num in numbers)
  {
    sum += num;
  }
  return sum;
}

Example for usage :

int newSum =0
newSum = Sum(1,2,3,4,5,6,7);

Such approach allows us:
1. To sum any amount of numbers we want.
2. We should not take care about nulls as in second (2) example
3. We not required to create instance of int[]

You Might Also Like

0 comments.

Popular Posts

Google+ Followers

Total Pageviews