Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>1. foreach and for</strong></p> <p>A <code>foreach</code> loop works with <a href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx" rel="noreferrer">IEnumerator</a>, when a <code>for</code> loop works with an index (in <code>object myObject = myListOfObjects[i]</code>, i is the index).</p> <p>There is a big difference between the two:</p> <ul> <li><p>an index can access directly any object based on its position within a list.</p></li> <li><p>an enumerator can only access the first element of a list, and then move to the next element (as described in the previous link from the msdn). It cannot access an element directly, just knowing the index of the element within a list.</p></li> </ul> <p>So an enumerator may seem less powerful, but:</p> <ul> <li>you don't always know the position of elements in a group, because all groups are not ordered/indexed.</li> <li>you don't always know the number of elements in a list (think about a linked list).</li> <li>even when it's ordered, the indexed access of a list may be based internally on an enumerator, which means that each time you're accessing an element by its position you may be actually enumerating all elements of the list up until the element you want.</li> <li>indexes are not always numeric. Think about <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer">Dictionary</a>.</li> </ul> <p>So actually the big strength of the <code>foreach</code> loop and the underlying use of <code>IEnumerator</code> is that it applies to any type which implements <code>IEnumerable</code> (implementing IEnumerable just means that you provide a method that returns an enumerator). Lists, Arrays, Dictionaries, and all other group types all implement IEnumerable. And you can be sure that the enumerator they have is as good as it gets: you won't find a fastest way to go through a list.</p> <p>So, the <code>for</code> loop can <em>generally</em> be considered as a specialized <code>foreach</code> loop:</p> <pre><code>public void GoThrough(List&lt;object&gt; myList) { for (int i=0; i&lt;myList.Count; i++) { MessageBox.Show(myList[i].ToString()); } } </code></pre> <p>is perfectly equivalent to:</p> <pre><code>public void GoThrough(List&lt;object&gt; myList) { foreach (object item in myList) { MessageBox.Show(item.ToString()); } } </code></pre> <p>I said <em>generally</em> because there is an obvious case when the <code>for</code> loop is necessary: when you need the index (i.e. the position in the list) of the object, for some reason (like displaying it). You will though eventually realize that <strong>this happens only in specific cases</strong> when you do good .NET programming, and that <code>foreach</code> should be your default candidate for loops over a group of elements.</p> <p>Now to keep comparing the <code>foreach</code> loop, it is indeed just an eye-candy specific while loop:</p> <pre><code>public void GoThrough(IEnumerable myEnumerable) { foreach (object obj in myEnumerable) { MessageBox.Show(obj.ToString()); } } </code></pre> <p>is perfectly equivalent to:</p> <pre><code>public void GoThrough(IEnumerable myEnumerable) { IEnumerator myEnumerator = myEnumerable.GetEnumerator(); while (myEnumerator.MoveNext()) { MessageBox.Show(myEnumerator.Current.ToString()); } } </code></pre> <p>The first writing is a lot simpler though.</p> <p><strong>2. while and do..while</strong></p> <p>The <code>while (condition) {action}</code> loop and the <code>do {action} while (condition)</code> loop just differ from each other by the fact that the first one tests the condition before applying the action, when the second one applies the action, then tests the condition. The <code>do {..} while (..)</code> loop is used quite marginally compared to the others, since it runs the action at least once even if the condition is initially not met (which can lead to trouble, since the action is generally dependent on the condition).</p> <p>The <code>while</code> loop is more general than the <code>for</code> and <code>foreach</code> ones, which apply specifically to lists of objects. The <code>while</code> loop just has a condition to go on, which can be based on anything. For example:</p> <pre><code>string name = string.empty; while (name == string.empty) { Console.WriteLine("Enter your name"); name = Console.ReadLine(); } </code></pre> <p>asks the user to input his name then press Enter, until he actually inputs something. Nothing to do with lists, as you can see.</p> <p><strong>3. Conclusion</strong></p> <p>When you are going through a list, you should use <code>foreach</code> unless you need the numeric index, in which case you should use <code>for</code>. When it doesn't have anything to do with list, and it's just a procedural construction, you should use <code>while(..) {..}</code>.</p> <p>Now to conclude with something less restrictive: your first goal with .NET should be to <em>make your code readable/maintainable</em> and <em>make it run fast</em>, in that order of priority. Anything that achieves that is good for you. Personally though, I think the <code>foreach</code> loop has the advantage that potentially, it's the most readable <strong>and</strong> the fastest.</p> <p><strong>Edit:</strong> there is an other case where the <code>for</code> loop is useful: when you need indexing to go through a list in a special way or if you need to modify the list when in the loop. For example, in this case because we want to remove every null element from myList:</p> <pre><code>for (int i=myList.Count-1; i&gt;=0; i--) { if (myList[i] == null) myList.RemoveAt(i); } </code></pre> <p>You need the <code>for</code> loop here because myList cannot be modified from within a <code>foreach</code> loop, and we need to go through it backwards because if you remove the element at the position i, the position of all elements with an index >i will change.</p> <p>But the use for these special constructions have been reduced since LINQ. The last example can be written like this in LINQ for example:</p> <pre><code>myList.RemoveAll(obj =&gt; obj == null); </code></pre> <p>LINQ is a second step though, learn the loops first.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload