One of the cool and yet most unknown feature of the C# is the yield keyword. The yield keyword is used in an iterator block to provide a value to the enumerator object or to signal the end of the iteration. When used the expression is evaluated and returned as a value to the enumerator object. Note the expression has to be implicitebly convertible to yield type of the iterator. Here is an example
public static IEnumerable<int> GetIntCollectionFromString(string SomeString)
string val = SomeString.Split(' ');
foreach (string token in val)
if (int.TryParse(token, out intVal))
yield return intVal;
Here since we are using the yield keyword the function will return the collection of intVal instead of the value of intVal. The statement will only return when the iteration of the loop is complete.
There are some limitation with the yield keywords.
- Unsafe blocks are not allowed
- Parameters to the method, operator, or accessor cannot be ref or out.