Skip to main content
Tweeted twitter.com/StackCodeReview/status/1348328767186472964
edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Enhance If else statement coding Add or subtract two numbers depending on dropdown selection

edited tags
Link
t3chb0t
  • 44.3k
  • 9
  • 84
  • 190

C# Enhance If else statement coding

I have a drop down list contain "Add" and "Subtract". When user select either one, it will call a function Calculate()

private int Calculate(string sAction)
{
    int iTotal = 0; 

    if(sAction == "Add")
    {
        iTotal = X + Y;
    }
    else if(sAction == "Subtract")
    {
       iTotal = X-Y;
   }  }      

    return iTotal;
}

I do not wish to hard coded it to compare the action. It seem like not fulfill Open Closed Principle. If I change the text in the drop down list, I need to change the function as well. May I know how I can improve this code? Thanks.

C# Enhance If else statement coding

I have a drop down list contain "Add" and "Subtract". When user select either one, it will call a function Calculate()

private int Calculate(string sAction)
{
   int iTotal = 0;
   if(sAction == "Add")
   {
       iTotal = X + Y;
   }
   else if(sAction == "Subtract")
   {
      iTotal = X-Y;
   }       
   return iTotal;
}

I do not wish to hard coded it to compare the action. It seem like not fulfill Open Closed Principle. If I change the text in the drop down list, I need to change the function as well. May I know how I can improve this code? Thanks.

Enhance If else statement coding

I have a drop down list contain "Add" and "Subtract". When user select either one, it will call a function Calculate()

private int Calculate(string sAction)
{
    int iTotal = 0; 

    if(sAction == "Add")
    {
        iTotal = X + Y;
    }
    else if(sAction == "Subtract")
    {
       iTotal = X-Y;
    }      

    return iTotal;
}

I do not wish to hard coded it to compare the action. It seem like not fulfill Open Closed Principle. If I change the text in the drop down list, I need to change the function as well. May I know how I can improve this code?

Source Link
Bubble Bub
  • 201
  • 2
  • 3
Loading