Enumerator Implementation: Use struct or class?

Reason List uses a struct enumerator is to prevent garbage generation in foreach statements. This is pretty good reason especially if you are programming for Compact Framework, because CF doesn't have generational GC and CF is usually used on low performance hardware where it can quickly lead to performance issues.

Also, I don't think mutable structs are source of problems in examples some posted, but programmers that don't have good understanding of how value types work.


An enumerator is inherently a changing structure, since it needs to update internal state to move on to the next value in the original collection.

In my opinion, structs should be immutable, so I would use a class.


Like this others, I would choose a class. Mutable structs are nasty. (And as Jared suggests, I'd use an iterator block. Hand-coding an enumerator is fiddly to get right.)

See this thread for an example of the list enumerator being a mutable struct causing problems...


The easiest way to write an enumerator in C# is with the "yield return" pattern. For example.

public IEnumerator<int> Example() {
  yield return 1;
  yield return 2;
}

This pattern will generate all of the enumerator code under the hood. This takes the decision out of your hands.