Yield

Yield keyword helps to return collection without backing collection.

Code below shows a method which iterates through collection of ints and returns every second number below specified value. Backing collection is returned.

        public static IEnumerable<int> GetEvenNumbersBelow(IEnumerable<int> numbers, int maxValue)
        {
            var numbersToReturn = new List<int>(); //creates backing collection
            foreach (var n in numbers)
            {
                if (n % 2 == 0)
                {
                    numbersToReturn.Add(n);
                }
                if (n == maxValue)
                {
                    return numbersToReturn;
                }
            }
            return numbersToReturn;
        }

Code below shows cleaner way to to the same as above.

        public static IEnumerable<int> GetEvenNumbersBelow(IEnumerable<int> numbers, int maxValue)
        {
            foreach (var n in numbers)
            {
                if (n % 2 == 0)
                {
                    yield return n;
                }
                if (n == maxValue)
                {
                    yield break;
                }
            }
            yield break;
        }
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