3

I have a method from a button click with the following code in c# (small golf scoring program I'm working on just for fun):

private void btnPlus_Click(object sender, EventArgs e)
{
    btnMinus.Enabled = true;
    if (f_intHoleNumber != 18) { f_intHoleNumber += 1; }
    if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
    txtHoleNumber.Text = f_intHoleNumber.ToString();            
}

I would like to refactor that and extract another method from it so I don't reuse code but i'm not sure if its possible to pass an operator (+=) as a parameter to a method. Can this be done?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
snapper
  • 210
  • 3
  • 14

4 Answers4

5

I don't think so. What about passing +1 or -1 to the method and multiplying it with the value to add or to subtract. For example:

public float calc(float val1, float val2, int op) 
{
    return val1 + op * val2;
}
daniel59
  • 906
  • 2
  • 14
  • 31
0

You can pass a method that does the adding and subtracting for you. You probably want to go that route. Pass Method as Parameter using C#

Community
  • 1
  • 1
JP Hochbaum
  • 637
  • 4
  • 15
  • 28
0

You could pass a Func<int, int> which accepts one int parameter and returns an int.

private void btnPlus_Click(object sender, EventArgs e)
{
    HandleHoleChange(currentHole => currentHole + 1);      
}

private void HandleHoleChange(Func<int, int> getNextHoleFunc)
{
    btnMinus.Enabled = true;
    if (f_intHoleNumber != 18) { f_intHoleNumber = getNextHoleFunc(f_intHoldNumber); }
    if (f_intHoleNumber == 18) { btnPlus.Enabled = false; }
    txtHoleNumber.Text = f_intHoleNumber.ToString();         
}
Steve Wong
  • 2,038
  • 16
  • 23
0

the accepted answer allows to pass a 0 which would mess up the calculation. If you want only to allow for addition or subtraction you can use a boolean variable to specify it in the parameterlist:

public float calc(float val1, float val2, bool add) 
{
    int op = add ? 1 : -1;
    return val1 + op * val2;
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76