C# Generic Enumeration Interfaces


This entry is part 6 of 7 in the series C# Generics

So far in this series we have described non-generic enumeration interfaces. The non-generic interface forms are for legacy code developed before C# 2.0 when generics were introduced. Why? The non-generic interface implementations we’ve been looking at so far are not type safe. They return a reference to type object, which must then be cast to the actual type. With the generic interfaces, however, the enumerator is type safe, returning a reference to the actual type.

In reality, you should mostly be using the generic versions of the interfaces, which are IEnumerable and IEnumerator. They’re called generic because they use C# generics. Using them is mostly the same as using the non-generic forms.

Enumerable classes and enumerators are used extensively in the .NET collection classes, so it’s important that you’re familiar with how they work. But now that you know how to create your own enumerable classes and enumerators, you might be pleased to learn that, starting with C# 2.0, the language provides a much simpler way of creating enumerators and enumerables. In fact, the compiler will create them for you!

Iterators

The construct that produces them is called an iterator. You can use the enumerators and enumerables generated by iterators wherever you would use manually coded enumerators or enumerables.

Series Navigation<< C# EnumeratorsC# Iterators >>