IDG Contributor Network: My two cents on the yield keyword in C#
The yield keyword, first introduced in C# 2.0, T returns an object that implements the IEnumerable interface. The IEnumerable interface exposes an IEnumerator that can used to iterate a non-generic collection using a foreach loop in C#. You can use the yield keyword to indicate that the method or a get accessor in which it has been used is an iterator.
There are two ways in which you can use the yield keyword: Using the "yield return" and the "yield break" statements. The syntax of both is shown below.
yield return <expression>;
yield break;
Why should I use the yield keyword?
The yield keyword can do a state-full iteration sans the need of creating a temporary collection. In other words, when using the "yield return" statement inside an iterator, you need not create a temporary collection to store data before it returned. You can take advantage of the yield return statement to return each element in the collection one at a time, and you can use the "yield return" statement with iterators in a method or a get accessor.
To read this article in full or to leave a comment, please click here