Csharp / C# Yield return example

C# yield return example.



Example:

using System;
using System.Collections.Generic;

    class ExampleYieldReturn
    {
        static void Main(string[] args)
        {
            //with every call it goes to where it left till it encounters yield return
            foreach(int n in GetNumbers())
            {
                Console.WriteLine(n);
            }

            Console.ReadLine();
        }

    public static IEnumerable<int> GetNumbers()
        {
            Console.WriteLine("Print number 52");
            yield return 52; // will go back to the caller ie foreach

            Console.WriteLine("Print number 63");
            yield return 63;// again will go back to the caller ie foreach

            Console.WriteLine("Print number 72");
            yield return 72;// again will go back to the caller ie foreach

        }

    }

Output:
Print number 52
52
Print number 63
63
Print number 72
72

Leave a Reply

  

  

  

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>