My Tutorials: C# Yield Keyword

Tuesday, 31 July 2012

C# Yield Keyword

The yield return and yield break keywords are shortcuts introduced in C# 3.0. They are designed to assist you by removing verbose code in methods that return IEnumerable types (i.e. IEnumerable <T>).

You can find the MSDN reference here.

Old Methodology

Usually a method that returns a collection consists of the following steps:
  1. Create an empty IEnumerable set. 
  2. Loop through some data (via a while, foreach or other construct) 
  3. Add to the set within your loop. 
  4. Exit the loop when some limit is reached. 
  5. Return the set 
Below is an example of the process required.

public IEnumerable<int> GetEvenNumbers(int maxCount)
        {
            //create and initialise IEnumerable container
            List<int> data = new List<int>();
            int currentNum = 0;
           
            //create and enter loop
            while (true)
            {
                if (currentNum % 2 == 0)
                {
                    //add the data to the IEnumerable container
                    data.Add(currentNum);
                }
                if (currentNum >= maxCount)
                {
                    //limit has been reach so we exit loop
                    break;
                }
            }
            //return the IEnumerable dataset
            return data;
        }


New Methodology

The new yield keywords allow you to shorten your code to only the following steps
  1. Loop through some data. 
  2. yield return within the loop 
  3. yield break if a limit is reached before the loop is completed. 
There is no need to explicitly create or return your IEnumerable collection.

The yield return statement appends a value to the IEnumerable collection. The yield break statement exits any looping construct to prevent more items being added to the return set. If you omit yield break, the loop exits as it normally would.

Below is an example using the yield keyword for the process required.

public IEnumerable<int> GetEvenNumbers(int maxCount)
        {
            int currentNum = 0;

            //create and enter loop
            while (true)
            {
                if (currentNum % 2 == 1)
                {
                    //add the data to the IEnumerable container using yield return
                    yield return currentNum;
                }
                if (currentNum >= maxCount)
                {
                    //limit has been reach so we exit loop using yield break
                    yield break;
                }
            }
        }


Performance

The difference between using the yield return and simply returning a set is subtle. Returning a set at the end of the method returns the entire set at once. The client must wait until the method is complete before it can use any values in the return set. Each time the yield return statement executes, the client has access to another element in the set. Essentially the set trickles back a little at a time. This can provide a gain in performance or perceived performance if you have a large set to return.

 Limitations

There are a few restrictions to using the yield keywords

  1. These keywords cannot appear in blocks marked "unsafe" 
  2. These keywords cannot appear in a method with ref or out parameters 
  3. The yield return statement is not allowed inside a try-catch block, although it may be located inside a try-finally block. 
  4. A yield break statement may not be located inside a finally block. 


No comments:

Post a Comment

Other Blogs and Sites

Social Media