Home > Net >  C# : IF ELSE replacement
C# : IF ELSE replacement

Time:09-22

In the application there are 5 methods,in all methods there are update queries. Methods are dependent on each other. If first method runs successfully, second is called; second runs successfully - third is called; third runs successfully - fourth is called; fourth runs successfully - fifth is called.

Here is code I have written

public void method1()    
{    
   int result = cmd.ExecuteNonQuery();    

   if(result > 0)    
   {    
        method2();    
   }    
}

public void method2()    
{    
    int result = cmd.ExecuteNonQuery();

    if(result > 0)    
    {    
        method3();    
    }    
}

public void method3()    
{    
    int result = cmd.ExecuteNonQuery();
 
    if(result > 0)    
    {    
        method4();    
    }    
}

public void method4()    
{    
    int result = cmd.ExecuteNonQuery();

    if(result > 0)  
    {    
        method5();    
    }    
}

I want to write this same code without using if statement, switch case or ternary operators. please guide me on how to do this.

CodePudding user response:

I would first chance the method signatures to return result.

You can then declare and array methods of Func<int> and initialize it to Method1, Method2, ...Methodn

You then just need a loop:

foreach (method in methods) {
    if (method() == 0)
        break; // or any other action.
}

Code can be added to handle something going wrong.

CodePudding user response:

@Tarik's answer is simple and does the job, I'd go with that.

There are other ways though.
You could, for example, create a Task for each method, and use one of the multiple options that c# TPL provides for that (for example, continuations)

Another simple thing, would be to make use of the short-circuit conditional operators, like this:

return cmd.ExecuteNonQuery1() > 0
    && cmd.ExecuteNonQuery2() > 0
    && cmd.ExecuteNonQuery3() > 0
    && cmd.ExecuteNonQuery4() > 0;
  • Related