yield return works only for IEnumerable<T>?

Jader Dias picture Jader Dias · Jul 1, 2009 · Viewed 14.7k times · Source

Can I use yield return when the return type is an IGrouping<TKey, TElement> or an IDictionary<TKey, TValue>?

Answer

Marc Gravell picture Marc Gravell · Jul 1, 2009

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.