Skip to content

Yield return

George George

Asked May 1, 2008, 6:24 AM EDT2 answers
Share
LinkedInX

Hello everyone,


I can not find too much materials about yield return. In MSDN sample,

http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx

what happens behind the scene of statement, "yield return result"?

I think what happens is a object instance which implements IEnumerable (collection pattern) interface is created (but what is the type of the instance? some C# internal type?), and each time "yield return result" is called, a new element is inserted into the internal array of the instance. Any more reference documents?


thanks in advance,
George

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    0
    ok, if you want to build your custom object container other than array or array list you can use iterator as alternative to enumerate the collection objects internally especially for the case when foreach is used to enumerate those internal objects.

    public class Container
    {
         ...
         private ArrayList oList = new ArrayList();
         .
    .
    .
    public IEnumerator GetEnumerator
    {
        foreach(CollectionObject obj in Container)
        {
            yield return obj;
        }
    }
    }

    In this case when yield return is used the compiler automatically generate  a class behind the scene witch implements the GetEnumerator, and MoveNext() methods  and of corse the current property.
    In my point of vue, yeld return is used in very special case as we can profit of the array and the array list GetEnumerator implementation to achieve the goal.
    0
  • 0

    I am interested in how internally the internal class is implemented, as you mentioned -- "a class behind the scene witch implements the GetEnumerator, and MoveNext() methods  and of corse the current property."

    I have this question is because, without understanding what are the code behind the scene, I find it is hard to understand how to use yield return. :-)

    Any reference materials?

     

    regards,

    George

    0