Search code examples
c#for-loopnested-loops

Breaking out of a nested loop


If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way?

I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop.

What is a quick and nice way of going about this?

I was thinking that exceptions aren't cheap/should only be thrown in a truly exceptional condition etc. Hence I don't think this solution would be good from a performance perspective.

I don't feel it it is right to take advantage of the newer features in .NET (anon methods) to do something which is pretty fundamental.


Solution

  • Well, goto, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return to exit back to the main code.

        // goto
        for (int i = 0; i < 100; i++)
        {
            for (int j = 0; j < 100; j++)
            {
                goto Foo; // yeuck!
            }
        }
    Foo:
        Console.WriteLine("Hi");
    

    vs:

    // anon-method
    Action work = delegate
    {
        for (int x = 0; x < 100; x++)
        {
            for (int y = 0; y < 100; y++)
            {
                return; // exits anon-method
            }
        }
    };
    work(); // execute anon-method
    Console.WriteLine("Hi");
    

    Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:

    // local function (declared **inside** another method)
    void Work()
    {
        for (int x = 0; x < 100; x++)
        {
            for (int y = 0; y < 100; y++)
            {
                return; // exits local function
            }
        }
    };
    Work(); // execute local function
    Console.WriteLine("Hi");