- C# Generics Introduction
- C# Generics 2
- C# Generic Constraints
- C# Generic Methods
- C# Enumerators
- C# Generic Enumeration Interfaces
- C# Iterators
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
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.