Tuesday, November 20, 2012

Is there a way of specifying which block or loop to break out of when working with nested loops?

Tags

 The easiest way is to use goto:
using System;
class BreakExample
{
 public static void Main(String[] args) {
  for(int i=0; i<3; i++)
  {
   Console.WriteLine("Pass {0}: ", i);
   for( int j=0 ; j<100 ; j++ )
   {
    if ( j == 10)
     goto done;
    Console.WriteLine("{0} ", j);
   }
   Console.WriteLine("This will not print");
  }
  done:
   Console.WriteLine("Loops complete.");
 }
}


EmoticonEmoticon