Hi, im sorry if this is the wrong place to post but its the only resource available to me at the time. While working on a project for school I have encountered an issue with getting my method to work.
My task is to create a single method that will carry out the arithmetic in each one of those if statements. I watched the video made by Brackeys about methods in c# however im still clueless on how to make this work.
Instead of this:
if (operator1 == "+") { decimal result = operand1 + operand2; txtResult.Text = result.ToString(); } else if (operator1 == "-") { decimal result = operand1 - operand2; txtResult.Text = result.ToString(); }
I should have this:
if (operator1 == "+") { //run method "calculate" } else if (operator1 == "-") { //run method "calculate" }
Below is a concept I have tried but was unsuccessful, any suggestions?
private static Boolean Calculate(this string logic, int operand1, int operand2) { switch (logic) { case "-": return operand1 - operand2; case "+": return operand1 + operand2; case "/": return operand1 / operand2; case "*": return operand1 * operand2; default: throw new Exception("invalid logic"); } }
For reference, this is the requirement in my project:
“Code a private method named Calculate that performs the requested operation and returns a decimal value. You will need two decimal variables for each operand and a string variable for the operator (to be performed on the 2 values).”