What does the Yield keyword mean in c# 2.0

Lets look at the following code:

class Program
    {
        public void PrintNumbers()
        {
            foreach (int i in Numbers())
            {
                Console.WriteLine(i.ToString());
            }
        }
        public IEnumerable Numbers()
        {
            yield return 1;
            yield return 2;
            yield return 3;
            yield return 4;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Consumer();
         
        }
}


The result is a lazy evaluation of a creation of an enumerable container. That is, each time you call the "Numbers" function - a new number is added to the collection and returned immediately to the "foreach" loop. 

You can stop the process by writing "yield break;". That will prevent the execution of the function "Numbers" in the current "foreach" statement.

Post a Comment

Previous Post Next Post