My code doesn’t terminate on a true condition if called from another method. For example,
void RunValidation()
{
if (NameEntered == string.Empty)
{
MessageBox.Show("No name has been entered");
return;
}
}
void CreateUser()
{
RunValidation();
//Run more code
}
If I call the validation method inside the create user method, the messagebox shows up but the rest of the code gets executed even though “return” was specified.
If the validation code is not inside a method and called directly in the CreateUser method, the rest of the code doesn’t run (which is what I want). I want to be able to call a validation method inside many other methods and if the conditions are true, to stop executing other code in the methods.
What is the correct way of doing this? Do I have to use some sort of try and catch?
You are returning from the
RunValidationmethod, not theCreateUsermethod. If you want to control the flow of theCreateUsermethod based on the results ofRunValidation, do something like this:The
returnstatement only affects the current method. Read more about thereturnstatement here.