How to use Yield in programming

In this post, we are going to look at a keyword in .NET that we all know exists but hardly ever use. 

 

And this is the yield keyword, which was introduced in C# 2. In this post, we will see what the yield keyword does, how to use it, and, of course, a small example.

 

 

1 - What is yield for in programming

In programming, we use yield to avoid having to create temporary data collections. 

However, when we use yield return, we must return an IEnumerable<T> since we need to use the IEnumerator interface.

 

We can refer to temporary data collections as those lists that we simply create to reuse immediately after in a foreach loop or similar.

public IEnumerable<string> FiltrarCochesGetNombres(List<Coche> coches)
{
    List<string> nombreCoches = new List<string>();
    foreach (Coche coche in coches)
    {
        if (coche.Marca == MarcaCcohe.Opel)
        {
            nombreCoches.Add(coche.Modelo);
        }
    }
    return nombreCoches;
}

We can see that we are only returning the models of the Opel brand.

 

If the logic of our code states that we are going to deal with that information later and we do not need it grouped, we can convert this method to use yield return:

public IEnumerable<string> FiltrarCochesGetNombresYield(List<Coche> coches)
{
    foreach (Coche coche in coches)
    {
        if (coche.Marca == MarcaCcohe.Opel)
        {
            yield return coche.Modelo;
        }
    }
}

 

 

2 - How does yield return work

I mentioned earlier that it is rare or uncommon to see code with methods containing yield, and this is because its execution seems "magical" but it really isn't. 

 

What the yield operator does is pause the execution of the iteration and return the value to the calling method so that it can continue with its execution. When it finishes, it will return to the next point in the iterator (the one in the method with yield return). 

public void Ejemplo()
{
    List<Coche> coches = new List<Coche>()
    {
        new Coche(MarcaCcohe.Audi, "A3"),
        new Coche(MarcaCcohe.Audi, "A5"),
        new Coche(MarcaCcohe.Opel, "Vectra"),
        new Coche(MarcaCcohe.Opel, "Astra"),
    };


    foreach (string modelo in FiltrarCochesGetNombresYield(coches))
    {
        Console.WriteLine($"El modelo del cohce es {modelo}");
    }

}

yield return explained

 

Note: when we use .Select() in a linq command, it is as if we are doing yield return

public IEnumerable<string> FiltrarCochesGetNombresYield(List<Coche> coches)
{
    return coches.Where(a => a.Marca == MarcaCcohe.Opel).Select(a => a.Modelo);
}

As long as we are returning IEnumerable<T> and not List<T>.

 

Which always helps improve performance. As those who follow me regularly know, I am quite picky about performance.

 

 

3 - Example of yield return in c# 

Personally, I was lucky enough to come across a question in a job interview I did, where the solution, or well, one solution was to use yield return.

 

The problem was the following: 

Implement a function that receives as a parameter an IEnumerable<T> and a batch size. The idea was to split that IEnumerable to return IEnumerable<List<T>> where each List<T> is equal to or less than the batch size:

public static IEnumerable<List<T>> Batch<T>(this IEnumerable<T> enumerable, int batchCount)
{
    // Code...
}

 

And this was the final result:

public static IEnumerable<List<T>> Batch<T>(this IEnumerable<T> enumerable, int batchCount)
{
    using (var enumerator = enumerable.GetEnumerator()) //get iteration for the Ienumerable.
    {
        while (enumerator.MoveNext())
        {
            //(re)start the values for the loop.
            List<T> result = new List<T>();
            var position = 0;
            do
            {
                result.Add(enumerator.Current);//add current iteration
                position++;

            } while (position < batchCount && enumerator.MoveNext());

            yield return result;
        }
    }
}

 

 

 

Conclusion

  • When we use yield return, what we do is pause the execution of the loop containing the yield return to continue with the method that called it.
  • For this reason, yield return can give us improvements in performance and RAM usage, which is always important.
  • We can use yield break to "break the loop" and thus use it inside a try{} catch{} block, but not in a finally.
  • Once we get used to using it, we can see that it is very useful and powerful, but unfortunately it is not very common. 

 

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café