You must Sign In to post a response.

Difference Between For Loop and ForEach

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


Comments

Author: Keerthy30 Mar 2007 Member Level: Silver   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.

Author: Mohammed Habeeb30 Mar 2007 Member Level: Silver   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.

Author: Sriman N Vangala01 Apr 2007 Member Level: Gold   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


Sign In to post your comments