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).
private IEnumerable StreamXElement(string inputUrl)
{
using (XmlReader reader = XmlReader.Create(inputUrl))
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "NodeIWant")
{
XElement el = XNode.ReadFrom(reader) as XElement;
if (el != null)
{
yield return el;
}
}
}
}
}
//consumption
var items = StreamXElement("helloworld.xml");
foreach(var item in items)
{
//now process the items
}
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
View Comments (2)
Nice clear example of yield but you are doing two if statements when only one is needed:
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "NodeIWant")
...surely this should be:
if (reader.NodeType == XmlNodeType.Element && reader.Name == "NodeIWant")
yes u are right:) It was written a while ago probably can fix it :)