Why does C#'s iterators feature spit out a class definition instead of a struct definition?

Q: Why does C#'s iterators feature spit out a class definition instead of a struct definition?

 

The iterators feature in C# generates classes that implement the enumerators required. This is detailed in the C# Specification. Why doesn't it use structs, which would be more efficient.

 

A:

 

There are two reasons.

 

(1) Naming. We generate classes that implement the enumerator interfaces and then use only the interface types in the public protocol. That way the names of the generated classes are purely an implementation detail. This is highly desirable from a versioning perspective. With a struct-based implementation, to get any of the efficiencies associated with structs we would have to use their types in the public protocol (using interfaces the structs would just get boxed). That in turns means we'd have to invent a name mangling scheme for the structs. In particular, iterators returning IEnumerable<T> would be complicated because a type could have multiple such members that differ only in their parameter list, meaning that the parameter list would have to be part of the mangled name.

 

(2) Structs don't work in recursive cases. For example, a TreeNode type could implement an iterator that recursively iterates first the left and then the right subtrees by foreach-ing contained members that are also of type TreeNode. With a struct-based implementation this would translate into an enumerator struct that contains a field of its own type--which isn't possible. (Think of it this way: A foreach statement obtains an enumerator and stores that in a local variable. In iterators, local variables are transformed into fields in the enumerator. A recursive iterator would therefore create a struct with a member of its own type.) You could argue that we can detect whether or not iterators are recursive and adjust our code generation scheme accordingly. However, you then end up with a versioning problem when a previously non-recursive iterator changes its (supposedly private) implementation to become recursive.

 

Anders (via Eric)