Back to C# School: Basics of Yield keyword


It is a common thing that, as and when we progress to use advanced language features and get some experience on few types, we almost tend to forget using the basics.

This post is all about an interesting C# stuff that exists right from C# 2.0!! Which you should be aware when writing code. Yes. If  you are an expert or if you already know the use of Yield keyword, stop reading right here.

Carry on if you dont mind reading it !

Yield (A C# language feature)

It is an iterator block to provide some value to the enumerator object or to signal the end of iteration.
According to Microsoft definition, the yield statement can only appear inside an iterator block, which might be used as a body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  1. Unsafe blocks are not allowed.
  2. Parameters to the method, operator, or accessor cannot be ref or out.
Let us see an example. Create a Console application and add this function below inside the class.
        public static IEnumerable<int> GetNumbers()
        {
            yield return 1;
            yield return 2;
            yield return 3;
            yield return 4;
        }
Now, from your main, you can call it like this

IEnumerable x = GetNumbers();

and now, to print the values from x, just use a loop and just add a break-point to above function and the below foreach loop to see how it works at debug time.

       foreach (int i in x)
       {
           Console.Write("{0} ", i);
       }

During debugging, the first thing you need to note is every single call maintains the state!! So only yield statement is executed at a time. That means, the call is made when required!

That’s pretty basic. Being said, If you want your function to return multiple values, you can use yield and finally at the caller end, you can iterate through the results. That’s fine. At first, Looks similar to a collection. Not a big deal.  Let us see one more example now to see the usefulness of yield.

Let us first write two extensions to int. The To extension prints a number serially.

       public static IEnumerable<int> To(this int value, int inclusiveMax)
        {
            for (int i = value; i <= inclusiveMax; i++)
                yield return i;
        }

And the Multiply Extension just multiplies a value with the multiplier.

    public static IEnumerable<int> Multiply(this IEnumerable<int> val, int multiplierval)
        {
            foreach (int v in val)
                yield return v * multiplierval;
        }

Now, you will see the .To extension for integers. So you can use something like

            var numbers = 1.To(10);
and doing a

        foreach (var i in numbers)
          {
             Console.WriteLine(i);
          }

Will print the values from 1 to 10.


Now, how about multiplying each of the above output value by 5?

          var op = 1.To(10).Multiply(5);
            foreach (var i in op)
                Console.WriteLine(i);

And you should see


This proves yield is useful. Isnt it? Here are few more things about Yield

  1. Interacts with the foreach-loop. It is a contextual keyword: yield is a keyword only in certain statements. It allows each iteration in a foreach-loop be generated only when needed. In this way it can improve performance.
  2. Yield is not a behavior of CLR but a C# language feature.
  3. This keyword is used to return items from a loop within a method and retain the state of the method through multiple calls. The call maintains the state and you don’t have to worry about doing it yourself!
Try it once!

To reach me, You can follow me on twitter @MSGuyTweets or find me on Facebook at Facebook.com/MysoreGuy

Popular posts from this blog

Facebook Javascript API : Feed and Share Dialog for Beginners

Real time Push Notifications with SignalR & PNotify (Pines Notify)

What's new and expected in .NET Framework 4.5