What is the difference between "for " and "foreach"

I always confused when should I use "for" and when foreach should be used...

when we talking about efficient which one is better to use?

thank you 

1/23/2008 7:30:09 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

12 Replies

Similar Articles

[PageSpeed] 34

its quite the same just a different way howto, never done or read about big differences about the both options:

 string [] n = new string[] {"test1", "test2"}

foreach(string a in n)


for(int i=0;i< i<n.Length;++i)


regards, roni
speed up your applications with distributed caching or replicated caching: http://www.sharedcache.com - its free!
1/23/2008 8:57:52 AM

thank you , How about efficient  ? any difference between them? thank you

1/23/2008 9:08:35 AM

Foreach is very useful in the situaltion when we need to loop though the list of objects


foreach(classname obj in listobject)



Alternatively we can use "for" here but foreach is best in this case. similarly when we need to loop through the array of variables which hols only the value then we have to use "for" option. 


1/23/2008 9:09:42 AM

Source MSDN:  

 In C#, the foreach keyword allows you to walk across items in a list, string, etc. and perform operations on each item. This is a very powerful tool, since it acts as a general-purpose enumerator over many types. The tradeoff for this generalization is speed, and if you rely heavily on string iteration you should use a For loop instead. Since strings are simple character arrays, they can be walked using much less overhead than other structures. The JIT is smart enough (in many cases) to optimize away bounds-checking and other things inside a For loop, but is prohibited from doing this on foreach walks. The end result is that in version 1, a For loop on strings is up to five times faster than using foreach. This will change in future versions, but for version 1 this is a definite way to increase performance.



Apurva Kaushal
1/23/2008 9:10:35 AM

When using a for Loop, if you wish to remove an item from the collection you are iterating through it can be done very easily. When using foreach you will get an exception stating that the item cannot be removed. This can be a real gotcha so keep your eyes open for it :)

Please mark the most helpful reply/replies as "Answer".
1/23/2008 9:18:03 AM

always use "for" when u know the counter range

and use  

"foreach" when u need to iterate through the collection which has implemented ienumerable

for more details go on following links: 



Always "Mark an Answer" to all those posts which gave you solution so other people could know the solutions.

Muhammad Adnan
.Net Evangelist
1/23/2008 9:42:11 AM

If you are going with array collection of known collection with controls and gridview, arraylist etc., then going with foreach is best. if you need to check any other condition before entering into loop then going for "for( )" is best.


1/23/2008 9:53:51 AM

Foreach statement is used in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information.

For loop can be used in simple itearion over an array until the desired condition is reached.

So i feel for simple itearions you can use for loops and iteration through the collection objects you can use foreach..

The difference lies depends on your requirement





[!!!!!!!Hopes this helps you!!!!!!!]

1/23/2008 10:22:57 AM


for (int i = 0; i < namesArrayList.Count; i++)    {        Response.Write(namesArray[i] + "...<br>");



This is just one of many problems with using a for loop.  You always have to "know" the count/length.  You have to know if it's a 0 or 1 based array, etc.   In this case we're working with strings, so it's pretty straightforward, but things also get more complicated when working with complex object types since we have to explicitly convert each object before we can use it.


 FOREACH: foreach (string name in namesArray)    {        Response.Write(name + "...<br>");   


 There are a few things that should be pointed out about this code as compared with the for syntax. 1.      You don't have to know the bounds/dimentions of the array  

2.      It automatically gives you an instance (of the right type) of whatever is collected by the array (a string in this case). 

3.      The syntax (and therefore the resulting code) is just so much cleaner

4.      This same syntax will work whether you're iterating over an array, ArrayListHashtable or any other type of collection.


In this Case Foreach gives better Performance. 


1/23/2008 10:27:14 AM

 sorry for asking about "namesArrayList.Count"

will it spend time to get the Count value? or don't?

thank you 


I just think

for ( int i =0 ; i<namesArrayList.Count ;i++)   → does it mean program need to spend time to go through all items just for get the "Count" value?

if it will spend time to get Count

does it mean use foreach will more efficient than use for?


1/23/2008 11:17:09 AM

For  is the best enumerator in that scenario.


1/23/2008 12:02:40 PM

foreach looppracticly used with controls e.g you have gridview with check boxes and admin have rights to delete more than one record from grid view. you can used foreach to iterate through each row of gridview

1/25/2008 11:09:14 PM

Similar Artilces:

Precedence of "where" ("of", "is", "will")?
Nobody on #perl6 today could answer this one. Is: Str | Int where { $_ } the same as: (Str | Int) where { $_ } or: Str | (Int where { $_ }) ? Followup questions, Mr. President: What kind of operators are "where", "of", "is", and "will"? Is there a reason that S03 doesn't list them? What are their precedence(s)? -- Chip Salzenberg - a.k.a. - <chip@pobox.com> Open Source is not an excuse to write fun code then leave the actual work to others. Chip Salzenberg writes: &...

.ALLCOL("%COLUMN%", " ", ", ", ", ")
Do you know anyway for me to exclude a subset of columns returned by this function. We have two columns (rec_user and rec_datetime) which are in all of our tables, but when generating triggers I want automatically generate a script which does not include those two columns but does include all other columns in that table. Bruce I should add that I am using PD Bruce "Bruce Lamb" <lamb.bruce@mayo.edu> wrote in message news:6HgI315nCHA.155@forums.sybase.com... > Do you know anyway for me to exclude a subset of columns returned by this > function. ...

Get "Mail"/"Get "News" / "Write"/"Post" buttons?
If the "Get Mail" button text changed to "Get News", and "Write" changed to "Post" when TB's in the news-reading mode, it would save me and probably others from constantly forgetting to make the change before proceeding. :-) Or is there an extension to do this which I don't know about? Thanks! Bob Bob P wrote: > If the "Get Mail" button text changed to "Get News", and "Write" > changed to "Post" when TB's in the news-reading mode, it would save me > and probably others...

quotes, quotes, quotes...
I am getting this error and I know what is causing it, but I have no idea how to fix it, any help would be great. The script steps through the /var/log/messages file on a linux server and puts The entries into a mysql database. However when it gets to the 'hlt' line in the messages file it just barfs. The single quotes are freaking it out. I know about quotes but not how to use in this situation. Thanks, Paul Error: May 27 17:53:00 localhost kernel: Checking 'hlt' instruction... OK. <----- doesn't like this in the messages file DBD::mysql::st exec...

"-" not "_"
I wrote a SQL statement in the data tab. I wrote a bunch of alaises as example ' word-type ' but when I hit the layout tab it converts the "-" to "_". So now my field name is ' word_type '. Is there any way to prevent this? CardGunner Don' use a hypen ( - ).  It isn't a valid character for column names.   See http://searchsqlserver.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid87_gci1188931,00.html   Here's an excerpt about column names: Letters as defined in the Unicode Standard 2.0 Decimal numbers from either B...

"Using" or "With"
Hi all Please can someone enlighten to me as regards the difference with the "Using" and "With" statement when accessing data - which is better, what are the limitations and/or any pointers. Many thanks. Regards DaveDavid WinchesterPlease mark as answer if this is the solution.  using gives you the ability to use the connection and it closes the connection directlly after you finish using it. and there is no need to try- cach - finaly. there is no limitation on using USING keywordMuhanad YOUNISMCSD.NETMy Blog || My Photos || LinkedIn I have a dataobject the re...

double quote
hello there...  i tried everything of think but not working the way i wanted to be... not sure what i'm missing...i'm generating a <span> in code behind and then using in javascript.... here is what i'm doing code behind: int i=0string _keywordID = "keyword";string _name = row["visit_info_nm"].ToString().Trim(); String _getElementByID = String.Format("<span id='{0}' OnClick = \"document.getElementById('{1}').value='{2}';\">{3}</span><br>", i, _keywordID, _name, _name); here is what it generate : <span id='1' OnClick = \"document.getElementById('keyword')...

Using "+" or "||"
Using SQLAnywhere 5.5.04, I've gotten into the habit of using "||" in ISQL to indicate a string concatenation. I needed to paste my SQL statement into the PowerBuilder script painter for some embedded SQL, and PB didn't like the "||" very much at all. I changed it to "+" and it seems to be ok. Do these two operators indicate ~exactly~ the same thing? moin, afaik these two's are not the same! if you're using "||" and any term is NULL then in the resultstring the term will be ignored if you use "+" then the resu...

"Me" is better than "You"
Yes I know, strings are frozen. But let me talk about it, I really can't get through the idea of a PC talkin to me. I consider my PC as an extension of myself, not a dumb companion who addresses Me as You. Yes there are times when I get angry with Him while I work and get wrong calculations etc.., but it really is my fault, Me using wrong istructions and eventually wanting to find someone else to blame, but it's Me. And yes, I consider Thunderbird my mail program, reading my mail on my PC as Me. So I personally like to have Me in the header bar as a compact address ...

replace the "." with a ","
Oi.... I need to build a small programm in ASP.NET and chose to use C# for it.Now i got everything working but there's one little problem.the first textbox is a double. I need to make it so that when someone enters a "." then it gets replaced by a ","any ideas?Ghan  string blah = "";blah = blah.Replace(".", ",");Ryan Ryan OlshanASPInsider | Microsoft MVP, ASP.NEThttp://ryanolshan.comHow to ask a question...

Replacing "\\" with "\"
Hi all I'm getting this value from a CheckBoxList control - a location of file, i have to remove "\\" and replace it with "\" and pass it to Query, how to do it, i tried with Replace, but coud'nt suceed. "\\\\Blaze10xp\\BLZ_SFS_07\\Sample Excel Files\\Excel Files\\report2.xls" thank's in advance - Prakash.C you tried Replace like this? string newstring = oldstring.Replace(@"\\",@"\");Plese, do not forget to click "Mark as Answer" on the post that helped you. Thanx!My blog: Scenes From A Developer Memory yes i tr...

"To" and "From" missing
When I print emails, the words "To" and "From" are blank, even though the "To" name and "From name (addresser, addressee) do show up. This is not a problem for other users on my system. Suggestions In mailbox right click, view. On the message window, right click and choose print options. Make sure print header is checked. -- Barry Merchant NSC Volunteer SysOp *** no email unless requested please!! *** > In mailbox right click, view. On the message window, right click and > choose print options. Make sure prin...

Regular Expression to remove "/", "\", "<", ">" and "="
Can anyone please show me the regular expression to reject a string ("<blue", "right>" etc.) which has the following expression in it: "/", "\", "<", ">" and "="  hi, It may Help u.. it is in Class file u may use this expressin in validation controls also. Regex objReg = new Regex(@"^[^,.?/\~|`;:'<>]*$", RegexOptions.Singleline); Regex objReg = new Regex(@"^[^,][^.][^?][^/][^\][^~|][^`][^;][^:][^'][[^<][^>]$", RegexOptions.IgnoreCase);Thanks &...

"JROC" / "JROK" / "JROCK" / "JROQ"
I just started a new contract and the tech lead told me that he wanted me to become familiar with something called "JROC" (among some other tools). I've been searching the web and I haven't found any dev tool called "JROC." Based on the name of the tool, it sounds like it encapsulates some javascript functionality. I have tried searching for different spellings - "JROK" / "JROCK" / "JROQ" but I haven't found any matches. Have you ever heard of a dev tool by this name?...

Web resources about - What is the difference between "for " and "foreach" - asp.net.getting-started

Resources last updated: 12/13/2015 8:42:23 AM