Explain Params Array in C# with an example.

 Posted by Rajnilari2015 on 8/16/2016 | Category: C# Interview questions | Views: 2317 | Points: 40
Answer:

If we want to pass variable number of arguments from calling function to called function, we can use the Params Arrays
e.g.

public class ParamTest


{

static void Main()

{

//calling function

PerformArithmeticOperation(20,10,"+"); //perform addition

PerformArithmeticOperation(20,10,"-"); //perform subtraction

PerformArithmeticOperation(20,10,"*"); //perform multiplication

PerformArithmeticOperation(20,10,"/"); //perform division

}



//called function

public static void PerformArithmeticOperation(params object[] items)

{

var result = 0;

switch (Convert.ToString(items[2])) //items[2] is the operator(s) i.e. +,-,*,/

{

case '+': result = Convert.ToInt32(items[0]) + Convert.ToInt32(items[1]); break;

case '-': result = Convert.ToInt32(items[0]) - Convert.ToInt32(items[1]); break;

case '*': result = Convert.ToInt32(items[0]) * Convert.ToInt32(items[1]); break;

case '/': result = Convert.ToInt32(items[0]) / Convert.ToInt32(items[1]); break;

default: Console.WriteLine("No such operation available");

}

Console.WriteLine(result);

}

}


We also can send no arguments. If we send no arguments, the length of the params list is zero.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response