C# 2.0 Yield Return Iterator


One interesting new feature of the C# 2.0 is the "yield" keyword.  Basically it is used to iterate through objects returned by a method. It creates a state engine in IL so you can create methods that retain their state and dont have to go through the pain of maintaining state in your code.

Here is a simple example that demonstrates how yield return can be used to maintain state in a method. Every time you call GetInt() you will receive a new incremented integer.

public static IEnumerable<int> GetInt()
{
   for (int i = 0; i < 5; i++)
       yield return i;
}

Here's the implementation.

class Program
{
        static void Main(string[] args)
        {
            foreach (int i in GetInt())
                Console.WriteLine("Got " + i.ToString());
        }

        public static IEnumerable<int> GetInt()
        {
            for (int i = 0; i < 5; i++)
                yield return i;
        }
}

Usually, the "yield" keyword will be useful when you implement the GetEnumerator() method of the IEnumerable interface

class TestClass: IEnumerable<int>
{
        #region IEnumerable<int> Members

        public IEnumerator<int> GetEnumerator()
        {
            for (int i = 0; i < 5; i++)
                yield return i;
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

}

Hopefully, this brief sample has helped you understand the new "yield" keyword and how it can be used.

Until next time,

Happy coding     

Up Next
    Ebook Download
    View all
    Learn
    View all