469,265 Members | 1,991 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,265 developers. It's quick & easy.

How do I exit a foreach loop

What is the command to exit a foreach loop prior to it's natural termination
(such as finding a specific string in an array)?
Nov 16 '05 #1
6 65461
break:

foreach (....)
{
..
break;
}

----
- Wilco Bauwer
Blog & Custom Controls @ http://wilcoding.xs4all.nl

Nov 16 '05 #2
if (something)
{
break;
}

--
Tim Wilson
..Net Compact Framework MVP

"Ray Stevens" <nf*@nospam.com> wrote in message
news:ei**************@tk2msftngp13.phx.gbl...
What is the command to exit a foreach loop prior to it's natural termination (such as finding a specific string in an array)?

Nov 16 '05 #3
Hi Ray,

In addition to the forementioned 'break' you can also use goto

foreach(this t of that)
{
if(condition)
goto SomeLabel;
}

SomeLabel: ;
--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #4
Yelp!

Sorry, major flashback of spaghetti goto's all over the place ;D

"Morten Wennevik" <Mo************@hotmail.com> wrote in message
news:opsmyc5rf4klbvpo@pbn_computer...
Hi Ray,

In addition to the forementioned 'break' you can also use goto

foreach(this t of that)
{
if(condition)
goto SomeLabel;
}

SomeLabel: ;
--
Happy Coding!
Morten Wennevik [C# MVP]

Nov 16 '05 #5
I rarely use them, but they are handy when stepping out of deep loops,
redoing loops etc.

And odd thing about C# labels is that they can only be inserted in front
of a code statement, hence the ; after label:

--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #6
"Morten Wennevik" <Mo************@hotmail.com> wrote in message
news:opsmyzgsa4klbvpo@pbn_computer...
I rarely use them, but they are handy when stepping out of deep loops,
redoing loops etc.
I had it hammered into me so hard that goto's are evil by my professors that
I still (9 years later) get twitchy when I see them ;D

Having spent all but the last year of my professional programming career
developing mainly in VB, you'd think I wouldn't still get cold shivers every
time I think of them, but there you go. Or maybe it's because I saw too much
goto horror...
And odd thing about C# labels is that they can only be inserted in front
of a code statement, hence the ; after label:
I did not know that.

<he says, glaring balefully at recently abandoned "The C# Programming
Language">

--
Happy Coding!
Morten Wennevik [C# MVP]

Nov 16 '05 #7

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Dave Spencer | last post: by
6 posts views Thread by Mike P | last post: by
18 posts views Thread by Ken Varn | last post: by
10 posts views Thread by fig000 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.