You must Sign In to post a response.
  • Category: .NET

    Difference Between For Loop and ForEach

    What is the Difference Between For Loop and For Each. Perfomance wise which option is better and why??
  • #116482
    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
    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
    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 :

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