Home > .NET, Java > C# – NAMED LOOPS … I miss them.

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.

Categories: .NET, Java
  1. Philip Rieck
    October 13, 2004 at 12:15 am

    “Named loops are not something you need very often, but occassionally they are useful”

    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.

  2. AndrewSeven
    October 13, 2004 at 12:17 am

    What about “break”?

  3. tech jobs
    October 24, 2004 at 7:50 am

    NAMES loops are like GOTO —

  4. http://
    March 17, 2008 at 2:48 pm

    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.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: