Tuesday 27 January 2015

Variable-Length Argument Lists (VARARGS)

Introduction:

Variable - length argument lists allow you to create methods that receive an arbitrary number of arguments. A one-dimensional array-type argument preceded by the keyword params in a method's parameter list indicates that the method receives a variable number of argument with the type of array elements. This use of params modifiers can occurs only in the last entry of the parameter list. While you can use method overloading and arraypassing to accomplish much of what is accomplished with "varargs"- another name for variable length argument lists-using the param modifiers is more concise.

Example:

  1. using System;  
  2. public class VarargsTest  
  3. {  
  4.     public static double Average(params double[] numbers)  
  5.     {  
  6.         double total = 0.0;  
  7.         foreach(double d in numbers)  
  8.             total += d;  
  9.   
  10.         return total/numbers.Length;  
  11.     }  
  12.   
  13.     public static void Main()  
  14.     {  
  15.         double d1 = 10.0;  
  16.         double d2 = 12.5;  
  17.         double d3 = 15.6;  
  18.         double d4 = 14.8;  
  19.   
  20.         Console.WriteLine( "d1 = {0:F2}\nd2 = {1:F2}\nd3 = {2:F2}\nd4 = {3:F2}", d1, d2, d3, d4 );  
  21.   
  22.         Console.WriteLine("Average of d1 and d2 is {0:F2}", Average(d1, d2));  
  23.         Console.WriteLine("Average of d1, d2 and d3 is {0:F2}", Average(d1, d2, d3));  
  24.         Console.WriteLine("Average of d1, d2, d3 and d4 is {0:F2}", Average(d1, d2, d3, d4));  
  25.   
  26.         Console.ReadLine();  
  27.     }  
  28. }  


Output of varargs
Fig: Screenshot of Output