I tried this earlier today:
public interface IFoo
{
IEnumerable GetItems_A( ref int somethingElse );
IEnumerable GetItems_B( ref in
C# iterators are state machines internally. Every time you yield return
something, the place where you left off should be saved along with the state of local variables so that you could get back and continue from there.
To hold this state, C# compiler creates a class to hold local variables and the place it should continue from. It's not possible to have a ref
or out
value as a field in a class. Consequently, if you were allowed to declare a parameter as ref
or out
, there would be no way to keep the complete snapshot of the function at the time we had left off.
EDIT: Technically, not all methods that return IEnumerable
are considered iterators. Just those that use yield
to produce a sequence directly are considered iterators. Therefore, while the splitting the iterator into two methods is a nice and common workaround, it doesn't contradict with what I just said. The outer method (that doesn't use yield
directly) is not considered an iterator.