Use of params modifier in C#

Posted by Abhisek under C# category on | Views : 2032
The 'params' modifier in C#

In C# 'params' parameter allows us to create a method that may be sent to a set of identically typed arguments as a single logical parameter. To better understand this situation let us see a program that calculates the average of any number of integers.

class ParamsUse
//method for calculating average
static int Average(params int[] values)
int sum = 0;
for(int i = 0;i < values.Length;i++)
sum + = values[i];
return (sum/values.Length);
static void Main(string[] args)
//pass int values in comma separated form
int average;
average = Average(34,56,78);
Console.WriteLine("The average is:-{0} ",average);

//pass an array of int
int[] data={34,56,78};
average = Average(data);
Console.WriteLine("The average of the array is:-{0} ",average);

The average is:- 56
The average of the array is:- 56


The Average() method is defined to take a parameter of array of integers. We can pass any number of integer to it to calculate the average. We can pass values to Average() in two ways as shown in the above program(pass values in comma separated form or pass values as array of integers). If you don't use the 'params' keyword in the definition of Average() then we could not pass values to it in comma separated form(It will give compilation error).

Comments or Responses

Login to post response