Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a condition to a method as parameter in C#

Tags:

c#

c#-4.0

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 ?

like image 511
user1340443 Avatar asked Apr 18 '12 06:04

user1340443


3 Answers

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();
}
like image 76
whoblitz Avatar answered Sep 30 '22 04:09

whoblitz


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;
    }
like image 27
nmaait Avatar answered Sep 30 '22 02:09

nmaait


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);
}
like image 20
Sergey Berezovskiy Avatar answered Sep 30 '22 03:09

Sergey Berezovskiy