params keyword in C#

params keyword allows to specify a method with parameter which takes variable number of arguments. It is an array type of parameter. With this type of parameter you can call a method each time with different number of arguments.
public static int Sum(params int[] args)
{
   int sum = 0;
   foreach (int ele in args)
      sum += ele;
   return sum;
}

Function Sum() shown in above code accepts parameter of type params. You can see that the parameter is same as array type,  but it differs from array in several ways
  • here you can pass multiple int elements instead of single array element.
  • size is not fixed, each time you may pass different no of elements
  • you can also call Sum() without passing single parameter in which case here, this function will return 0.
You can call Sum() as:
Sum(1, 2);                    // will return 3
Sum(new int[] { 1, 2, 3 });   // will return 6
Sum();                        // will return 0

Points to note while using params:
  • Each function can only have one params type of parameter
  • It must be the last parameter in argument list
  • It is perfectly fine even if you don't pass any parameter for params type of parameter.

aj1490

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comments: