For those who want a different option, what 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 did an example compiling on
link