The way it was described to me is yield is like rasing an enumeration event. The following code for example will flatten out a control collection hierarchy and allow you to work with it like a flat array:
public static IEnumerable<Control> All(this ControlCollection controls)
{
foreach (Control control in controls)
{
//this part is important
foreach (Control grandChild in control.Controls.All())
yield return grandChild;
yield return control;
}
}
This will allow you to create a loop that will display all controls in a page:
foreach(Control c in Page.Controls.All())
{
Debug.Print(c.Id);
}
They are a pretty useful construct, but they are not always necessary. They are used more when you do not control how the enumeration will be initiated, but you want to provide an implementation of an enumeration.
Anthony Terra
Marked as answer by mou_inn on Apr 17, 2012 07:34 AM
aterra
Participant
910 Points
162 Posts
Re: what is the actual use of yield keyword
Apr 15, 2012 09:38 PM|LINK
The way it was described to me is yield is like rasing an enumeration event. The following code for example will flatten out a control collection hierarchy and allow you to work with it like a flat array:
public static IEnumerable<Control> All(this ControlCollection controls) { foreach (Control control in controls) { //this part is important foreach (Control grandChild in control.Controls.All()) yield return grandChild; yield return control; } }This will allow you to create a loop that will display all controls in a page:
foreach(Control c in Page.Controls.All()) { Debug.Print(c.Id); }They are a pretty useful construct, but they are not always necessary. They are used more when you do not control how the enumeration will be initiated, but you want to provide an implementation of an enumeration.