AnonDCX AnonDCX - 1 month ago 5
C# Question

Return keyword not halting execution of method

I have three classes (Class A, Class B and Class C). Class B holds one method (Method 1) while Class C holds one method (Method 2). The prime purpose for Class A is to do the calling for each method in their respective classes.

Class A calls method 1 inside Class B:

private void buttonSave_Click(object sender, EventArgs e) {
Process[] processes = Process.GetProcessesByName("WINWORD");// Kill Word Process
ProcessForm processForm = new ProcessForm();
Validation validateForm = new Validation();

validateForm.Validate(this);//Call to method 1
processForm.CreateDocument();//Call to method 2 still gets called after a return from this method...?
}


which holds a condition to test if a variable is true or false and if it is true I need it to return and NOT return to the calling class (Class A) until the value is false:

//Class B
if (textIsEmpty == true)
{
MessageBox.Show("Fill in the text fields");
return;//Shouldnt this halt execution?
}


My problem is that Method 2 is still being called from Class C even with the return. I can only speculate that it has something to do with returning to a separate class.

Help would be appreciated.

Answer

return ends the currently executing method ( returning the control back to the caller ). The next line within the caller is the call to another method. This is where the code is expected to continue.

If the next line should not be executed you should indicate by returning eg a boolean in method1 and wrapping the call to method 2 in an if statement.


//Class B
if (textIsEmpty == true) {
  MessageBox.Show("Fill in the text fields");
  return false;//Shouldnt this halt execution?
}

and then

private void buttonSave_Click(object sender, EventArgs e) {
  Process[] processes = Process.GetProcessesByName("WINWORD");// Kill Word Process
  ProcessForm processForm = new ProcessForm();
  Validation validateForm = new Validation();

  if (validateForm.Validate(this) ) { //Call to method 1
    processForm.CreateDocument();//Call to method 2 only if indicated by method 1      
  }             
}