exit loop iteration case

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!
 
N

Navid

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
}
}
 
J

Jeff Johnson

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.
 
J

Jon Skeet [C# MVP]

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
 
P

Peter Morris

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
}
}
 
J

Jon Skeet [C# MVP]

<

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
 
P

Peter Morris

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


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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top