Pass += or -= as a parameter in c#

Viewed 624

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?

4 Answers

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;
}
Related