How to pass variable number of arguments using Params in c#?

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 1065
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;

}
Console.WriteLine(result);
}
}

Comments or Responses

Login to post response