That means that if you iterate through a generic collection of value type elements
??”List
, for example??”then no boxing is performed at all. If the old
interface had been used instead, then although we wouldn??™t have incurred the boxing
cost while storing the elements of the list, we??™d still have ended up boxing them when
we retrieved them using foreach!
All of this is done for you under the covers??”all you need to do is use the foreach
statement in the normal way, using the type argument of the collection as the type of
the iteration variable, and all will be well. That??™s not the end of the story, however. In
the relatively rare situation that you need to implement iteration over one of your own
types, you??™ll find that IEnumerable extends the old IEnumerable interface, which
means you??™ve got to implement two different methods:
IEnumerator GetEnumerator();
IEnumerator GetEnumerator();
Can you see the problem? The methods differ only in return type, and the rules of
C# prevent you from writing two such methods normally. If you think back to section
2.2.2, we saw a similar situation??”and we can use the same workaround. If you
implement IEnumerable using explicit interface implementation, you can implement
IEnumerable with a ???normal??? method. Fortunately, because IEnumerator
extends IEnumerator, you can use the same return value for both methods, and
implement the nongeneric method by just calling the generic version.
Pages:
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198