Search code examples
c#.netienumerable

yield return works only for IEnumerable<T>?


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


Solution

  • 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.