Home > DeveloperSection > Forums > Main method returns if submethod has stoped by return in C#
Ankita Pandey
Ankita Pandey

Total Post:183

Points:1285
Posted on    January-27-2015 10:08 PM

 ASP.Net C# 
Ratings:


 1 Reply(s)
 404  View(s)
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

 



Mark Devid
Mark Devid

Total Post:101

Points:707
Posted on    January-27-2015 10:35 PM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick