How do foreach loops work in C#? -
which types of classes can use foreach
loops?
actually, strictly speaking, need use foreach
public getenumerator()
method returns bool movenext()
method , ? current {get;}
property. however, common meaning of "something implements ienumerable
/ienumerable<t>
, returning ienumerator
/ienumerator<t>
.
by implication, includes implements icollection
/icollection<t>
, such collection<t>
, list<t>
, arrays (t[]
), etc. standard "collection of data" support foreach
.
for proof of first point, following works fine:
using system; class foo { public int current { get; private set; } private int step; public bool movenext() { if (step >= 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); } } }
how work?
a foreach loop foreach(int in obj) {...}
kinda equates to:
var tmp = obj.getenumerator(); int i; // c# 4.0 while(tmp.movenext()) { int i; // c# 5.0 = tmp.current; {...} // code }
however, there variations. example, enumerator (tmp) supports idisposable
, used (similar using
).
note difference in placement of declaration "int i
" inside (c# 5.0) vs. outside (up c# 4.0) loop. it's important if use i
in anonymous method/lambda inside code-block. story ;-p
Comments
Post a Comment