Boost Coding Productivity with Yield Keywords in C#

Introduction

In the modern programming world, as a developer, we are all required to upgrade ourselves to learn new things every day which will help us to improve and increase productivity in our day-to-day work. Also, it is very important always to code smart to impress with our work when we are working with a big challenging team. In C# there are plenty of new features added in its latest versions and we missed playing with them. Today we are going to see one of the featurescalled yield return, yield break, and the difference between the usual C# break with the yield break keyword with some real-time examples. Let’s dive into the yield universe.

What is the Yield Keyword?

Here is the official definition of the yield keyword in Microsoft's official documentation.

“yield statement in an iterator to provide the next value or signal the end of an iteration”

The yield keyword helps to perform a custom iteration over a collection like List, Arrays, etc.

We cannot directly use the yield keyword without the return and break statement in C#. It has two forms,

  1. yield return
  2. yield break

Let’s have a quick example for yield return and yield break,

Let’s create a simple C# console project and here I named it YieldExample.

Create simle program

Yield return in C#

Returns an expression at each iteration.

Let's create a simple method in the program.cs file which will return odd numbers from 1 to 10 as IEnumerable<int>.

namespace YieldExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to yield universe..!");

            // get list of odd number from 1 to 10.
            foreach(var oddNum in getOddNumbers())
            {
                Console.WriteLine(oddNum.ToString());
            }
            
            Console.ReadKey();
        }

        public static IEnumerable<int> getOddNumbers()
        {
            for(int i = 1;i<= 10; i++)
            {
                if (i % 2 == 1)
                {
                    yield return i;
                }
            }
        }
    }
}

Now run the application and check, you can see the odd numbers from 1 to 10.

Run the application and check

But yes, I know you are very curious to know what yield return does here, right?

let’s set a breakpoint in the code line numbers 12 and 24 and check what’s happening around here,

Break point

Odd number string

Yes, you noticed here? The getOddNumbers() method will return an odd number at each iteration to the caller method and return back to continue the iteration. The process continues until the iteration is over. Also, the yield will preserve the last iteration(i is 1) in memory to continue the iteration when it comes back from the caller method. (it will loop from 2).

What is the use of Yield in real-time?

Yield helps us to reduce memory usage. Not clear at the moment? Let’s have another example,

Consider you want to return a list from a method, what we usually write in the C# is, we create a temporary list inside the method and will add the items into that temporary list and finally, we return them back to the caller method like below,

namespace YieldExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to yield universe..!");

            // get list of odd number from 1 to 10.
            foreach (var oddNum in getOddNumbers())
            {
                Console.WriteLine(oddNum.ToString());
            }

            Console.ReadKey();
        }

        public static IEnumerable<int> getOddNumbers()
        {
            List<int> result = new List<int>();
            for (int i = 1; i <= 10; i++)
            {
                if (i  == 5)
                {
                    result.Add(i);
                }
            }
            return result;
        }
    }
}

Create temp list to bind

It is okay to have a temp list when the list will consume very little memory, but It will impact the performance of our application where it is required to return a huge list. Here, the yield keyword comes into the picture which it helps us to return the item in every iteration without forming a temp list.

Yield break in C#

Terminates the iteration.

Let's get the list of numbers from the getListOfNumbers() method and break the iteration using the yield break keyword when the iteration value is equal to 5.

namespace YieldExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to yield universe..!");

            // get list of odd number from 1 to 10.
            foreach(var oddNum in getListOfNumbers())
            {
                Console.WriteLine(oddNum.ToString());
            }
            
            Console.ReadKey();
        }

        public static IEnumerable<int> getListOfNumbers()
        {
            for (int i = 1; i <= 10; i++)
            {
                if (i == 5)
                {
                    yield break;
                }
                yield return i;
            }
        }
    }
}

Yield example

Now, let’s remove the yield break and simply apply the usual c# break keyword and check what is the output.

namespace YieldExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to yield universe..!");

            // get list of odd number from 1 to 10.
            foreach (var oddNum in getOddNumbers())
            {
                Console.WriteLine(oddNum.ToString());
            }

            Console.ReadKey();
        }

        public static IEnumerable<int> getOddNumbers()
        {
            for (int i = 1; i <= 10; i++)
            {
                if (i  == 5)
                {
                    break;
                }
                yield return i;
            }
            
        }
    }
}

Welcome to yield universe

It provides the same result. Then what is the difference between yield break and normal break keywords? Confusing right? Don’t worry, let’s see another example to find the difference between them.

Difference between yield break and normal break keyword

Let us alter the above program and add one extra outer loop in the same program.

Here are the code changes

namespace YieldExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to yield universe..!");

            // get list of odd number from 1 to 10.
            foreach(var oddNum in getListOfNumbers())
            {
                Console.WriteLine(oddNum.ToString());
            }
            
            Console.ReadKey();
        }

        public static IEnumerable<int> getListOfNumbers()
        {
            for (int k = 0; k < 2; k++) // Extra outer loop
            {
                Console.WriteLine();
                for (int i = 1; i <= 10; i++) // Inner loop
                {
                    if (i == 5)
                    {
                        yield break;
                    }
                    yield return i;
                }
            }
        }
    }
}

Local variable

Still, the output is the same because the yield break will break the complete iteration and return to the caller method.

The break keyword will break the inner loop and again go back to the outer loop to continue the iteration until the outer loop condition fails. Below is the output for the break keyword,

Internal class program

See, the output from 1 to 4 is printed twice as a break statement only will break the inner loop iteration and continue back again from the outer loop.

Conclusion

Hope we have learned some high-level understanding of the yield keyword and the difference between the yield break keyword and the usual C# break keyword. See you all in the next useful programming concepts.

Happy Learning 😊


Similar Articles