C# - NAMED LOOPS ... I miss them.

Named loops give the ability to extend flow control with markers.  Cynics would argue they are glorified gotos but in that case, they probably don't like continue anyway!

Here is a simple contrived example:

1namespace NamedLoopExample 
2{
3 public class NamedLoops
4 {
5 public void Example()
6 {
7 Product[] products = new Product[] { new Product() };
8 Sku[] skus = new Sku[] { new Sku(), new Sku() };
9 // in Java: ProductLoop: for (int n = 0; n < products.Length; n++)
10 for (int n = 0; n < products.Length; n++)
11 {
12 for (int i = 0; i < skus.Length; i++)
13 {
14 // find the right sku
15 // continue with the next product not sku
16 // in Java: continue ProductLoop;
17 }
18 // some other logic to do something else
19 // since the sku wasn't found
20 }
21 }
22 }
23 public class Product { }
24 public class Sku { }
25}


Named loops are not something you need very often, but occassionally they are useful. The alternative
of tracking a bool to know when to break is really ugly.  Often you can refactor the logic possibly into separate methods (with Extract Method) to make the flow easier to manage.

Does anyone else miss named loops?

UPDATE (10/13/2004):  There is a great discussion of GOTO that also references named loops on the C2 wiki.

3 Comments

  • &quot;Named loops are not something you need very often, but occassionally they are useful&quot;



    Much like GOTO. However, they're never needed. And much like GOTO they make the code harder to read for very little gain in productivity.



    I'd probably say that if you want a named loop to get rid of the ugly bool, you've found a pretty strong code smell.



    While I would probably be labeled by some as a cynic, I personally don't miss them.

  • What about &quot;break&quot;?

  • Named loops? I miss them. To Philip (and other would-be cynics), how would you solve the problem outlined by Jonathan? You'll have to set up some sort of ugly flagging system. Or, in my experience, you can sometimes get around this with recursion. Neither is very nice.

Comments have been disabled for this content.