Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Actually, <strong>strictly</strong> speaking, all you need to use <code>foreach</code> is a public <code>GetEnumerator()</code> method that returns something with a <code>bool MoveNext()</code> method and a <code>? Current {get;}</code> property. However, the most <strong>common</strong> meaning of this is "something that implements <code>IEnumerable</code>/<code>IEnumerable&lt;T&gt;</code>, returning an <code>IEnumerator</code>/<code>IEnumerator&lt;T&gt;</code>.</p> <p>By implication, this includes anything that implements <code>ICollection</code>/<code>ICollection&lt;T&gt;</code>, such as anything like <code>Collection&lt;T&gt;</code>, <code>List&lt;T&gt;</code>, arrays (<code>T[]</code>), etc. So any standard "collection of data" will generally support <code>foreach</code>.</p> <p>For proof of the first point, the following works just fine:</p> <pre><code>using System; class Foo { public int Current { get; private set; } private int step; public bool MoveNext() { if (step &gt;= 5) return false; Current = step++; return true; } } class Bar { public Foo GetEnumerator() { return new Foo(); } } static class Program { static void Main() { Bar bar = new Bar(); foreach (int item in bar) { Console.WriteLine(item); } } } </code></pre> <p><strong>How does it work?</strong></p> <p>A foreach loop like <code>foreach(int i in obj) {...}</code> kinda equates to:</p> <pre><code>var tmp = obj.GetEnumerator(); int i; // up to C# 4.0 while(tmp.MoveNext()) { int i; // C# 5.0 i = tmp.Current; {...} // your code } </code></pre> <p>However, there are variations. For example, it the enumerator (tmp) supports <code>IDisposable</code>, it is used too (similar to <code>using</code>).</p> <p><strong>Note the difference</strong> in the placement of the declaration "<code>int i</code>" <em>inside</em> (C# 5.0) vs. <em>outside</em> (up C# 4.0) the loop. It's important if you use <code>i</code> in an anonymous method/lambda inside your code-block. But that is another story ;-p</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. 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