Can I tell the outer function to return, from inside its local function?

718 views Asked by At

I have a IEnumerator and I need to do some checks inside the function and if some of those checks fail, I need to do some maintenance and then exit the IEnumerator. But when I write yield break into the inner function, it thinks I'm trying to return from that inner function.

I guess I could just write yield break after the inner function calls, but I'd like to remain DRY.

private IEnumerator OuterFunction()
{
    //bla bla some code

    //some check:
    if (!conditionA)
        Fail();

    //if didn't fail, continue normal code

    //another check:
    if (!conditionB)
        Fail();

    //etc....

    //and here's the local function:
    void Fail()
    {
        //some maintenance stuff I need to do

        //and after the maintenance, exit out of the IEnumerator:
        yield break;
        //^ I want to exit out of the outer function on this line
        //but the compiler thinks I'm (incorrectly) returning from the inner function Fail()
    }
}
1

There are 1 answers

1
user85567 On

You will need to put the yield break in the OuterFunction(). See What does "yield break;" do in C#?

private IEnumerator OuterFunction()
{
    //bla bla some code

//some check:
if (!conditionA){
    Fail();
    yield break;
}

//if didn't fail, continue normal code

//another check:
if (!conditionB){
    Fail();
    yield break;
}

//etc....

//and here's the local function:
void Fail()
{
    //some maintenance stuff I need to do

    //and after the maintenance, exit out of the IEnumerator:

    //^ I want to exit out of the outer function on this line
    //but the compiler thinks I'm (incorrectly) returning from the inner function Fail()
}
}