Main method returns if submethod has stoped by return in C#

Total Post:183

Points:1285
C# 
 954  View(s)
Ratings:
Rate this:

Say I have two EventHandlers:

private void button1_click(object sender, EventArgs e)
{
   //Do first stuffs
 
   button2_click(sender, e);
 
   //Do second stuffs
}
 
private void button2_click(object sender, EventArgs e)
{
   //Do somthing
 
   if(myCondition) return; //Also return in button1_click
 
   //Do somthing else
}

Is there any way to return in button1_click and skip //Do second stuffs part if button2_clickhas stopped with return?

I'm looking for a way other than using a public bool variable to check if myCondition in button2_click is true

 

  1. Post:102

    Points:714
    Re: Main method returns if submethod has stoped by return in C#

    My recommendation is to extract the meaningful portions of each handler into methods that can be called independently and can have useful return values. This is particularly important for your second button's handler, since the handler for button1 also depends on it.

    Upon extracting the code, you can transform the extracted method into a boolean function, and can depend upon the return value to continue your process.

    private void button1_click(object sender, EventArgs e)
    {
       ThingToDoForButton1();
    }
     
    private void button2_click(object sender, EventArgs e)
    {
       ThingToDoForButton2();
    }
     
    private void ThingToDoForButton1()
    {
        // do something
     
        if (ThingToDoForButton2())
        {
             // do something else
        }
    }
     
    private bool ThingToDoForButton2()
    {
        //Do something
     
        if(/* some condition */) return false;
     
        //Do something else
     
        return true;
    }

    Of course, it is up to you to provide meaningful names for your methods, once extracted, and to consider breaking down your code into additional smaller functions if the "do something" and "do something else" parts are not insignificant.

      Modified On Apr-09-2018 12:09:30 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!