Reputation: 787
I have methods
public void x()
{
y();
z();
}
public void y()
{
if(some condition) return;
some code...
}
public void z()
{
somecode...
}
I know that the return statement in method y()
will be returned without executing anything else in that method if the somecondition
condition is met and will be returned back to method x()
and execute the method z()
. But is there way to return from method x()
as well without executing method z()
?
I cant change any constraints or edit method y
Upvotes: 0
Views: 79
Reputation: 66489
One option is to return a bool
value from y()
.
public void x()
{
var isValidY = y();
if (isValidY)
z();
}
public bool y()
{
if(some condition) return false;
// some code...
return true;
}
public void z()
{
// some code...
}
If you can't change y()
then you'll have to take the advice Enigmativity left in the comments, and repeat the logic represented by some condition
:
public void x()
{
y();
if (some condition) return;
z();
}
public bool y()
{
if (some condition) return;
// some code...
}
Upvotes: 1
Reputation: 1504
If you can't change the method signatures, make a global flag variable:
private bool shouldContinue = true;
public void x()
{
y();
if(shouldContinue)
z();
}
public void y()
{
if(some condition)
{
shouldContinue = false;
return;
}
some code...
}
public void z()
{
somecode...
}
Upvotes: 0
Reputation: 29266
Make y()
return some kind of code to let x()
know whether to call z()
or not.
public void x()
{
if (y())
{
z();
}
}
// Return true if processing should continue.
//
public bool y()
{
if(some condition) return false;
some code...
return true;
}
public void z()
{
somecode...
}
Upvotes: 5