Yield keyword in C Sharp

Hi,

 

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(' ');
    int intVal;
    foreach (string token in val)
    {
        if (int.TryParse(token, out intVal))
        {
            yield return intVal;
        }
        else
        {
            yield break;
        }
    }
}
 

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.

  1. Unsafe blocks are not allowed
  2. Parameters to the method, operator, or accessor cannot be ref or out.

Vikram

8 Comments

Comments have been disabled for this content.