Search This Blog

Thursday, January 2, 2014

C# Params keyword

Params enables methods to receive variable numbers of parameters. With params, the arguments passed to a method are changed by the compiler to elements in a temporary array. This array is then used in the receiving method.
Example

class Program
{
    static void Main()
    {
 //
 // Call params method with different parameters.
 //
 int sum1 = SumParameters(1);
 int sum2 = SumParameters(1, 2);
 int sum3 = SumParameters(3, 3, 3);
 int sum4 = SumParameters(2, 2, 2, 2);
 
 Console.WriteLine(sum1);
 Console.WriteLine(sum2);
 Console.WriteLine(sum3);
 Console.WriteLine(sum4);
    }

    static int SumParameters(params int[] values)
    {
 
 // Loop through and sum the integers in the array and add to total.
 
 int total = 0;
 foreach (int value in values)
 {
     total += value;
 }
 return total;
    }
}

No comments:

Post a Comment