Search code examples
c#loopsgoto

Is this a safe way to use goto?


foreach (var thing in things)
{
    tryagain:
    string thing.var1 = ThisCanReturnNullSometimes();
    if (thing.var1 == null)
    {
        goto tryagain;
    }
}

I know ideally you don't want a method that can "fail" but I'm working with the youtube data API and for some reason some calls just.. don't follow through.

It seems like a short and sweet way to reattempt the iteration, but i've never used a goto before and I've only heard people say don't use it.


Solution

  • Most programs can be expressed without goto. In this particular case, a loop is a far more readable construct, because it says pretty much what you want it to say:

    string x;
    do {
        x=CanReturnNullSometimes();
    } while (x==null);
    

    One nice thing about this loop is that the readers always know its post-condition: the only way this loop can terminate is that x becomes non-null. You can also add safety check to ensure that you are not calling the method too many times.