What is yield in C#

Yield is a keyword that used in iterator methods in C#.

It is good practice to use yield return when return enumerable and we don’t have all the results in that point. For example:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> lst = new List<int> { 1, 2, 3, 4 };

            IEnumerable<int> enumrable = MyFunc(lst);
            foreach (var i in enumrable)
            {
                Console.WriteLine(i);
            }

        }

        public static IEnumerable<int> MyFunc(IEnumerable<int> inputCollection)
        {
            foreach (var element in inputCollection)
                yield return element;
        }
    }
}

The results:

Capture

 

Also, it is reasonable to use yield return when we want iterate through the large block of information – database, big  file, etc. And we won’t load everything in memory first. So, in other words, yield is a nice and convenient way to iterate through the block without loading everything at once.

Another usage of yield is yield break:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            IEnumerable<int> enumrable1 = null;
            IEnumerable<int> enumrable2 = EnumerateThroughNull(enumrable1);
            foreach (var i in enumrable2)
            {
                Console.WriteLine(i);
            }

        }

        public static IEnumerable<int> MyFunc(IEnumerable<int> inputCollection)
        {
            foreach (var element in inputCollection)
                yield return element;
        }
        public static IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
        {
            if (source == null)
            {
                yield break;
            }

            foreach (T item in source)
                yield return item;
        }
    }
}

In this example you want return iterator that returns nothing if the source is null or empty. Without yield break it becomes impossible to return an empty set inside the iterator. So, if you removes yield break and your function becomes look like this:

public static IEnumerable<T> EnumerateThroughNull<T>(IEnumerable<T> source)
{
    foreach (T item in source)
        yield return item;
}

you will get NullreferenceException.

Share this post:Tweet about this on TwitterShare on Facebook0Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this