Forums » .NET » .NET »

Difference Between For Loop and ForEach


Posted Date: 30 Mar 2007      Posted By:: Ankit     Member Level: Gold    Member Rank: 0     Points: 2   Responses: 3



What is the Difference Between For Loop and For Each. Perfomance wise which option is better and why??



Responses

#116482    Author: Keerthy      Member Level: Silver      Member Rank: 0     Date: 30/Mar/2007   Rating: 2 out of 52 out of 5     Points: 2

In case of For-each the size of the collection is not necessary where as in case of for loop you need to specify the size of the collection.

 
#116489    Author: Mohammed Habeeb      Member Level: Silver      Member Rank: 0     Date: 30/Mar/2007   Rating: 2 out of 52 out of 5     Points: 2

The foreach loop is excellent for iterating through collections.
For loop is more versatile, but not as easy as foreach because, the logic of iterating should be properly implemented. For loop is not also optimized for iterating Objects(Collection)

The main drawback of 'foreach' loops is that each value extracted is read-only. So entring a new value or removing to the collection is not possible.


 
#116690    Author: Sriman N Vangala      Member Level: Gold      Member Rank: 116     Date: 01/Apr/2007   Rating: 2 out of 52 out of 5     Points: 2

foreach is used on top of collections to traverse through while for can be used on anything for the same purpose. ex: For int total = 0; for(int i = 0; i < myInterger.Length; i++) { total += myInterger[i]; } Foreach int total = 0; foreach(int i in myInterger) { total += i; } Refer : http://www.codeproject.com/csharp/foreach.asp




 
Post Reply

 This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.



Return to Discussion Forum
Start new thread

Subscribe to Subscribers
Awards & Gifts
Talk to Webmaster Tony John
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India