Using Yield Keyword in C#

 Yield is a keyword which is used to get list of  items from a loop. The method implementing yield keyword returns an enumerable object.Yield retains the state of the method during the multiple calls. That means yield returns a single element to the calling function and pause the execution of the current function. Next time it will resume the execution from that point only and return the next element. It is a reliable and more efficient way to get a list of values from a function. This is the keyword provided in C#.net 2.0 onward.Yield makes the developer life more simpler. The compiler when compiles the code containing the yield keyword, creates a good  amount  of IL(Intermediate Language) code. Basically we do not have to worry about these codes, that is the headache of the compiler.:)
Ex:

private void MainProcess()
{
    string[] nameList = GetNames();
    foreach(string name in nameList)
    {
        //do the processing here.
    }
}
 
private string[] GetNames()
{
    List names = new List();
 
    for (int i = 0; i < 10; i++)
    {
        names.Add("Name:" + i);
    }

    return names.ToArray();
}

The following code shows the way Yield implements the same thing.

private void MainProcess()
{
    foreach(string name in GetNames())
    {
        //do the processing here.
    }
}
 
private IEnumerable GetNames()
{
    for (int i = 0; i < 10; i++)
    {
        yield return "Name:" + i;
    }
}

Here, the implementation in case of Yield is simple and straight forward. The GetNames() method iterates through the for loop and returns a value each time it is called. The yield return is different from the return keyword. Where the return keyword stops the execution of the method and returns the control to the calling method, yield return pauses the execution of the method and returns the control to the calling method. The next time when we call the GetNames() method the execution resumes from the point where it left last time.

The yield keyword can take any of the following two forms:
yield return ;
– yield break;

Where yield return returns the values to the calling method and paused the execution, yield break ends the execution and permanently returns the control to the calling function.

There are few restrictions while implementing the yield keyword. These are: – The yield statement can only appear inside an iterator block. – Unsafe blocks are not allowed. – Parameters to the method, operator, or accessor cannot be ref or out. – A yield statement cannot appear in an anonymous method.

– Keep the enumeration code as simple as you can because debugging it afterwards is almost impossible.

Initially Yield may seems like little bit confusing but once you start implementing it you will find it very interesting and powerful.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!