Having issues with creating a method, WFA C#

Updated on October 5, 2018 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on October 5, 2018

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).”

 

  • Liked by
  • Quasee
Reply
0 on October 5, 2018

Your Calculate method is set to return a bool. Try changing it to int, and make sure all paths can return a value. As it is, if they input an illegal operator, nothing gets return, you just throw an exception. Even if it just returns null.

 

  • Liked by
Reply
Cancel