How to pass variable number of arguments using Params?

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

Posted by: Snaini on: 10/7/2015 Level:Starter | Status: [Member] | Points: 10
Ya nice one.If we use class also its better
public class Operation{
int a{get;set;}
int b{get;set;}
char value{get;set;}
}
PerformArithmeticOperation(Details);

public static void PerformArithmeticOperation(Operation Details)

{

var result = 0;

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

{

case '+': result = //
case '-': result =//

case '*': result = //

case '/': result = //



}

Console.WriteLine(result);

}

}

Login to post response