I have 2 buttons doing the same function but in different condition. there code is something like this.
private void button1_Click(){
// do function1
if(condition){
...decrement an integer
//do function2
}
}
private void button2_Click(){
// do function1
if(another condition){
...increment an integer
//do function2
}
}
Can I pass condition1 and condition2 and increment, decrement to a method ?
Yes you can. But you are still limited in what you can do. Consider this
public void Foo(Action action, Func<Boolean> someCondition) {
if (someCondition() == true) action();
}
You can try something like this:
private void buttonClick()
{
DoSomething(condition ? true : false);
}
private void DoSomething(bool increment)
{
// do stuff
if (increment)
++index;
else
--index;
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With