March 2004
Intermediate to advanced
560 pages
26h 47m
English
public interface IEnumerable
{
// Methods
IEnumerator GetEnumerator ();
}
|
BA It is interesting to look at how the C# foreach support works with types that implement IEnumerable. For a C# program that looks like this:
foreach (int v in collection) { ... }
The C# compiler generates code that looks something like this:
1: IEnumerable ie = (IEnumerable) collection;
2: IEnumerator e = ie.GetEnumerator();
3: try {
4: while (e.MoveNext()) {
5: int v = (int) e.Current;
6: ...
7: }
8: }
9: finally {
10: if (e is IDisposable) {
11: ((IDisposable)e).Dispose();
12: }
13: }
In line 1, you see the first thing we do is cast the collection to the IEnumerable interface. Then in line 2 we get the IEnumerator and in line 4 we start iterating ... |
Read now
Unlock full access