Information Technology Reference
In-Depth Information
The Non-Interface Enumerator
You've just seen how to use the IEnumerable and IEnumerator interfaces to create useful enu-
merables and enumerators. But there are drawbacks to this method.
First, remember that the object returned by Current is of type object . This is fine for refer-
ence types, but for value types, this means that before they are returned by Current , they must
be boxed to turn them into object s. They must then be unboxed again after they have been
received from Current . This can exact a substantial performance penalty if it needs to be done
on large amounts of data.
Another drawback of the non-generic interface method is that you've lost type safety. The
values being enumerated are being handled as object s, and so can be of any type. This elimi-
nates the safety of compile-time type checking.
You can solve these problems by making the following changes to the enumerator/
enumerable class declarations.
￿
For the enumerator class
-Do not derive the class from IEnumerator .
-
Implement MoveNext just as before.
Implement Current just as before, but have as its return type the type of the items
being enumerated.
-
You do not have to implement Reset .
-
￿
For the enumerable class
-
Do not derive the class from IEnumerable .
Implement GetEnumerator as before, but have its return type be the type of the
enumerator class.
-
Figure 20-5 shows the differences. The non-generic interface code is on the left, and the
non-interface code is on the right. With these changes, the foreach statement will be perfectly
happy to process your collection, but without the drawbacks just listed.
Search WWH ::




Custom Search