Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: for vs foreach  (Read 3025 times)

0 Members and 1 Guest are viewing this topic.

Treval

    Topic Starter


    Hopeful

    Thanked: 14
    for vs foreach
    « on: April 14, 2010, 09:45:39 AM »

    When would one use for and when foreach?
    What are the pros and cons for each of these condition structures?

    BC_Programmer


      Mastermind
    • Typing is no substitute for thinking.
    • Thanked: 1140
      • Yes
      • Yes
      • BC-Programming.com
    • Certifications: List
    • Computer: Specs
    • Experience: Beginner
    • OS: Windows 11
    Re: for vs foreach
    « Reply #1 on: April 14, 2010, 09:53:56 AM »
    foreach enumerates through a collection faster then using for and accessing that collection by index. for is for looping when you know the starting and ending conditions, or for more general purpose looping.

    everything you can do with a for() loop, you can do with a do....while loop, it's really just a shorthand. in the same way that foreach is a shorthand for a for loop something like this (psuedocode):

    enumerator = collection.GetEnumerator();
    for(loopvalue=enumerator.GetFirst();!Enumerator.HasItems();loopvalue=enumerator.GetNext())
    {


    }

    instead of
    foreach(loopvalue in collection)
    {


    }

    the second one is a little easier to read :P
    I was trying to dereference Null Pointers before it was cool.