yield return works only for IEnumerable<T>?

yield return works for exactly 4 cases:

  • IEnumerable
  • IEnumerable<T>
  • IEnumerator
  • IEnumerator<T>

This is because it has to build a state machine internally; a dictionary (etc) wouldn't be possible with this. You can of course just return a suitable type instead.


You could however return IEnumerable<KeyValuePair<K,V>> that would be similar to a dictionary. You would then yield return KeyValuePairs. You could even wrap this with another method that creates a dictionary out of the return. The only thing the first method would not guarantee is uniqueness in the keys.


Answer: No. A yield return statement can be used only if the return type is IEnumerator, IEnumerator<T>, IEnumerable, or IEnumerable<T>.

From §8.14 of the C# 3.0 spec:

The yield statement is used in an iterator block (§8.2) to yield a value to the enumerator object (§10.14.4) or enumerable object (§10.14.5) of an iterator or to signal the end of the iteration.

From §10.14.4:

An enumerator object has the following characteristics:

  1. It implements IEnumerator and IEnumerator<T>, where T is the yield type of the iterator.

[...]

From §10.14.5:

An enumerable object has the following characteristics:

  1. It implements IEnumerable and IEnumerable<T>, where T is the yield type of the iterator.

[...]