Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>?

like image 504
Jader Dias Avatar asked Jul 01 '09 19:07

Jader Dias


People also ask

How does yield return work?

When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

What is the return type of IEnumerable?

IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).

What is yield return in C #?

The yield return statement returns one element at a time. The return type of yield keyword is either IEnumerable or IEnumerator . The yield break statement is used to end the iteration. We can consume the iterator method that contains a yield return statement either by using foreach loop or LINQ query.

What is the difference between yield and return in C#?

The only difference between yield and return is whenever yield statement is encountered in a function, the execution of function is suspended and a value is send back to the caller but because of yield whenever the function is called again, the execution of function begin where it left off previously.


1 Answers

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.

like image 126
Marc Gravell Avatar answered Oct 13 '22 00:10

Marc Gravell