The yield keyword

What is it?

If you google yield, you’ll find this kind of definition: “yield is a syntactic  sugar that bla bla bla”.

Yeah, ok… But in practice, what is it?

In a few words, yield enables you to return more than once in a method where the return type is an Enumerable.

When to use?

It is not my intention here to think of all the situations where yield can be applied, but I will give you some examples:

  • If you have a service layer and, in the middle of a heavy treatment, want to warn your view in what step you are
    • Uploading a lot of files (status: 1 of 5000…)
    • Executing heavy transactions (including this, deleting that…)
    • Etc
  • If you don’t know when the process will end and want to know what are you doing
    • Treating files in a folder that can be changed during the process
    • Etc
  • Etc

There are many things that you can do with yield.

You can use yield inside a while, for, foreach, but you don’t need at all to be inside a loop to use this.

Be creative!

Show me an example!

This example was the simplest I could think of.

In the code below we cannot see where we are

using System;
using System.Threading;

namespace MyCode
{
    class Program
    {
        static void Main(string[] args)
        {
            new ServiceLayer().DoHeavyJob(loops: 3, timeInsideStep: 1000);
        }
    }

    class ServiceLayer
    {
        public void DoHeavyJob(int loops, int timeInsideStep)
        {
            while(loops-- > 0)
            {
                Thread.Sleep(timeInsideStep);
            }
        }
    }
}

How can we use yield plus Enumerable return type to solve this?

using System;
using System.Collections.Generic;
using System.Threading;

namespace MyCode
{
    class Program
    {
        static void Main(string[] args)
        {
            var enumerable = new ServiceLayer().DoHeavyJob(loops: 3, timeInsideStep: 1000);

            foreach(var step in enumerable)
            {
                Console.WriteLine("{0} steps remaining...", step);
            }

            Console.WriteLine("Success!");
        }
    }

    class ServiceLayer
    {
        public IEnumerable<int> DoHeavyJob(int loops, int timeInsideStep)
        {
            while(loops > 0)
            {
                yield return loops--;
                Thread.Sleep(timeInsideStep);
            }
        }
    }
}

 

Now is your turn!

Let us know if it was helpful for you!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s