So C# what is the yield keyword? The yield keyword in C# is basically an iterator, its a form of syntactic sugar added from C# 2.0 to create IEnumerable and IEnumerator objects, thus returning one element at a time.

From MSDN documentation it states.

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it appears is an iterator. You use an iterator to perform a custom iteration over a collection. The following example shows the two forms of the yield statement.

Personally I have found using yield helpful in XML streaming where I have a very large document but would like to combine the use of XElement with XMLReader, such that the memory is not consumed like XDocument (where it loads the entire document into memory).

From the above code it will return an IEnumerable of XElement for us to process.

Some notes on using yield.

The declaration of an iterator must meet the following requirements:

  • The return type must be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.
  • The declaration can’t have any ref or out parameters.

Also one cannot use yield in:

  • Anonymous methods
  • Methods that contain unsafe blocks