Why not to extract duplicated code to methods?
private void Function1()
{
// do function1
}
private void Function2()
{
// do function2
}
private void button1_Click()
{
Function1() ;
if(condition)
{
//...decrement an integer
Function2();
}
}
private void button2_Click()
{
Function1();
if(another condition)
{
//...increment an integer
Function2();
}
}
If you have many similar methods with same structure, then consider creating
private void DoSomething(Func<bool> condition, Action action)
{
Function1();
if (condition())
{
action();
Function2();
}
}
And invoke it this way:
private int value;
private void button2_Click()
{
DoSomething(() => value < 5, () => value++);
}
Of course, if you need to pass some parameters to condition or action you should change Func
or Action
type. Also use Func
instead of Action
if you need to return some value from action.
private int value;
private void button2_Click()
{
DoSomething((x) => x % 2 == 0, (x) => x.ToString());
}
private void DoSomething(Func<int, bool> condition, Func<int, string> action)
{
Function1();
if (condition(value))
{
string result = action(value);
Function2();
}
}
If your condition and action is not that simple, use named methods instead of lambdas:
private bool FooCondition(int x)
{
// complex condition here
}
private string BarAction(int x)
{
// complex action here
}
private void button2_Click()
{
DoSomething(FooCondition, BarAction);
}