Prev | Current Page 188 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Fortunately we??™ll see in chapter 6 that C# 2 takes a large amount of the work
away from enumerators in many cases. I??™ve shown the ???full??? version so you can
appreciate the slight wrinkles that have been introduced by the design decision for
IEnumerable to extend IEnumerable.
Implements
IEnumerable
explicitly
C
Implements
IEnumerator.Current
implicitly
D
Implements
IEnumerator.Current
explicitly
E
Proves that
enumerable
type works
F
92 CHAPTER 3 Parameterized typing with generics
We only need the trick of using explicit interface implementation twice??”once
for IEnumerable.GetEnumerator C, and once at IEnumerator.Current E. Both of
these call their generic equivalents (B and D respectively). Another addition to
IEnumerator is that it extends IDisposable, so you have to provide a Dispose
method. The foreach statement in C# 1 already called Dispose on an enumerator if
it implemented IDisposable, but in C# 2 there??™s no execution time testing
required??”if the compiler finds that you??™ve implemented IEnumerable, it creates
an unconditional call to Dispose at the end of the loop (in a finally block).
Many enumerators won??™t actually need to dispose of anything, but it??™s nice to know
that when it is required, the most common way of working through an enumerator
(the foreach statement F) handles the calling side automatically.


Pages:
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200