Explain params modifier in C#?

 Posted by CGN007 on 5/30/2012 | Category: C# Interview questions | Views: 2716 | Points: 40

Suppose we want to pass different number of parameters to a function.To achive this we can create params parameter.
The params modifier is used to declare an array parameter that will be receive zero or more parameters.The array size is equal to the number of elements passed to the method.

 public int sum(params int[] nums)

int total=0;
if (nums.Length == 0)
Console.WriteLine("No arguments.");
return 0;
for (int i = 0; i < nums.Length; i++)
total = total + nums[i];
return total;

Calling the function
class Program

static void Main(string[] args)
BaseClass baseObj = new BaseClass();
Console.WriteLine(baseObj.sum(1, 3));
Console.WriteLine(baseObj.sum(1, 3, 5));

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response