exit loop iteration case

  • Thread starter Thread starter csharpula csharp
  • Start date Start date
C

csharpula csharp

Hello,

I am iterating through objects and have the following case:

foreach (classA objectA in classAList)
{
if (classA.count> 0)
{
//now I need to get out of the foreach loop if so,otherwise to keep
iterating
}

}

What is the best way to do it?

Thanks!
 
csharpula said:
Hello,

I am iterating through objects and have the following case:

foreach (classA objectA in classAList)
{
if (classA.count> 0)
{
//now I need to get out of the foreach loop if so,otherwise to keep
iterating
}

}

What is the best way to do it?

Thanks!

to simply just get out of the iteration is some condition becomes true
you can use break;


foreach (classA objectA in classAList)
{
if (classA.count> 0)
{
break;
//now I need to get out of the foreach loop if so,otherwise to
keeiterating
}
}
 
I am iterating through objects and have the following case:

foreach (classA objectA in classAList)
{
if (classA.count> 0)
{
//now I need to get out of the foreach loop if so,otherwise to keep
iterating
}

}

What is the best way to do it?

You've been given the answer, but just for completion, the opposite (so to
speak) of "break" is "continue." It's used far less and some would probably
argue that if you structure your code right you'll never need to use it.
 
You've been given the answer, but just for completion, the opposite (so to
speak) of "break" is "continue." It's used far less and some would probably
argue that if you structure your code right you'll never need to use it.

Those are probably the same people who always use a single exit point
from a method, regardless of how much less readable that makes the
code ;)

Jon
 
Those are probably the same people who always use a single exit point
from a method, regardless of how much less readable that makes the
code ;)
<

Despite people I know advocating having only a single exit point from every
method, I am always much happier doing this

public void DoSomethingIfNotNull(object instance)
{
if (instance == null)
return;

//lots of code here
}

than this

public void DoSomethingIfNotNull(object instance)
{
if (instance != null)
{
//lots of code here
}
}
 
<

Despite people I know advocating having only a single exit point from every
method, I am always much happier doing this

<snip>

Exactly. It's just a case of being pragmatic.

Jon
 
Exactly. It's just a case of being pragmatic.


I tried it once;
but hated seeing;
text that looked
like this; // :-)
}
}
}
}
}
}
 
Back
Top