For anyone who wants a different option, how about?
if (theOperator == "+") {
operacao = soma;
}
else if (theOperator == "-") {
operacao = subtracao;
}
else if (theOperator == "*") {
operacao = multiplicacao;
}
else if (theOperator == "/") {
operacao = divisao;
}
else {
MessageBox.Show("Este simbolo não é reconhecido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
total2 = operacao(total1,double.Parse(total3.ToString()));
Mine may be the least recommendable, but at least it’s more fun.
Making use of encapsulated functions and lambda expressions.
Here is the complete code:
using System;
public class Program
{
public static void Main()
{
Calcula("+",1,2);
Calcula("-",1,2);
Calcula("*",1,2);
Calcula("/",1,2);
}
public static void Calcula(string theOperator, double total1, double total3)
{
double total2 = 0;
//Encapsulo os métodos
Func<double,double,double> soma = (a,b) => a + b;
Func<double,double,double> subtracao = (a,b) => a - b;
Func<double,double,double> multiplicacao = (a,b) => a * b;
Func<double,double,double> divisao = (a,b) => a / b;
Func<double,double,double> operacao = null;
if (theOperator == "+") {
operacao = soma;
}
else if (theOperator == "-") {
operacao = subtracao;
}
else if (theOperator == "*") {
operacao = multiplicacao;
}
else if (theOperator == "/") {
operacao = divisao;
}
else {
MessageBox.Show("Este simbolo não é reconhecido", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
total2 = operacao(total1,double.Parse(total3.ToString()));
Console.WriteLine(total2);
}
}
I made an example compiling in
https://dotnetfiddle.net/T01SsB
ok if the switch is better I’ll leave the switch but thanks anyway for the help
– pekira
Why would it be more readable in this case?
– Maniero
At least for me, I think the switch is a much more readable way to understand the code, because Voce groups all the checks into simple conditionals
– KhaosDoctor