VitzzViperzz
Well-known member
Hello,
So I just randomly decided to make a calculator to test what delegates could do. So I thought that I would make a set of delegates under Class Program
I then got the input and used a few (a lot more than a few) if and else if statements to point the program in the right direction for the correct calculation:
But my question is, how can I make the section with the if statements more efficient. because this seems like a pain to do for larger applications.
Also, any suggestions on anything other than Delegates to achieve the same results? More method based?
Thanks :star:
So I just randomly decided to make a calculator to test what delegates could do. So I thought that I would make a set of delegates under Class Program
C#:
delegate double CalculationProcess(double param1, double param2);
static double Add(double param1, double param2) => param1 + param2;
static double Subtract(double param1, double param2) => param1 - param2;
static double Multiply(double param1, double param2) => param1 * param2;
static double Divide(double param1, double param2) => param2 / param2;
I then got the input and used a few (a lot more than a few) if and else if statements to point the program in the right direction for the correct calculation:
C#:
CalculationProcess process;
Console.WriteLine("Enter a number: ");
string userInput1 = Console.ReadLine();
Console.WriteLine("Enter a second number: ");
string userInput2 = Console.ReadLine();
double param1 = Convert.ToDouble(userInput1);
double param2 = Convert.ToDouble(userInput2);
Console.WriteLine(" Enter A for add\n Enter S for subtract\n Enter M for Multiply\n Enter D for Divide");
string userDecision = Console.ReadLine();
if (userDecision == "A")
{
process = new CalculationProcess(Add);
}
else if (userDecision == "S")
{
process = new CalculationProcess(Subtract);
}
else if (userDecision == "M")
{
process = new CalculationProcess(Multiply);
}
else
{
process = new CalculationProcess(Divide);
}
Console.WriteLine($"The result is: {process(param1, param2)}");
Console.ReadKey();
But my question is, how can I make the section with the if statements more efficient. because this seems like a pain to do for larger applications.
Also, any suggestions on anything other than Delegates to achieve the same results? More method based?
Thanks :star: