tags:

views:

240

answers:

4

I need C# equivalent to Java’s continue ?

i have

for (String b : bar) {
    <label>
    try {
    }
    catch (EndpointNotFoundException ex) {
    continue <label>
    }
  }

how can i simulate this in C#. i need that when i get exception that i repeat code not go on.

+5  A: 

If you only need to continue to the next loop iteration, use continue.

c# also has labels (which you can jump to with goto), but please don't use them.

Gabe Moothart
You forgot to add that goto's are evil :p
Stormenet
Only non-local goto's are evil. C# disallows non-local goto.
Robert Davis
From a discussion on loops and continues (in Eric's replies to comments): "Note that the C# goto was carefully designed to be less hazardous than other languages' gotos." http://blogs.msdn.com/ericlippert/archive/2010/01/11/continuing-to-an-outer-loop.aspx
Brian
`continue` is just a special kind of `goto`, so if `goto`s are really evil, then `continue` is a special kind of evil (which happens to be generally safer due to the restrictions). Everything has its place and proper use, including (rarely) `goto`s.
jball
This is the only time goto should be used.
Jonathan Allen
+3  A: 

Use goto <label>;

Robert Davis
so goto are not so evil. Thx foy our help, i will use goto <label>
senzacionale
@senzacionale, `goto` is not evil, just very dangerous. The fact that `goto` exists in C# does not make it safe - and your chosen use seems unsafe in a number of ways.
jball
+4  A: 

Why not simply add a control variable?

foreach (String b in bar) {
  bool retry;
  do {
    retry = false;
    try {
      // ...
    }
    catch (EndpointNotFoundException ex) {
      retry = true;
    }
  } while (retry);
}

or

var strings = bar.GetEnumerator<string>();
var retry = false;
while (retry || strings.Next()) {
  var b = strings.Current;
  retry = false;
  try {
    // ...
  }
  catch (EndpointNotFoundException ex) {
    retry = true;
  }
}
Fábio Batista
Much easier to read and understand.
FrustratedWithFormsDesigner
+1 This is the right answer.
Gabe Moothart
+2  A: 

I don't think what you're trying to do is wise at all - do you have any reason to expect that you won't hit a scenario where you always get an exception on a particular iteration?

Anyhow, to do what you want to do without goto, look at this:

foreach (String b in bar) { 
    while(!DidSomethingWithThisString(b))
        ;
  } 

bool DidSomethingWithThisString(string b)
{
    try { 
    } 
    catch (EndpointNotFoundException ex) { 
        return false;
    } 
    return true;
}
jball