I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this:
private static IEnumerator<TextBox> FindTextBoxes(Control rootControl) { foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2 != null) { yield return textBox2; } } }
Using it like this:
foreach(TextBox textBox in FindTextBoxes(this)) { textBox.Height = height; }
But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator.
Is there a way to do this without having to create a separate class with a GetEnumerator() method?
IEnumerable is the return type from an iterator. An iterator is a method that uses the yield return keywords.
The IEnumerable interface permits enumeration by using a foreach loop. However, the GetEmunerator method of the IEnumerable interface returns an IEnumerator interface. So to implement IEnumerable , you must also implement IEnumerator .
IEnumerable interface has a method called GetEnumerator() which returns an object implemented IEnumerator. Let's do an example: PowersOfTwo class implements IEnumerable so any instance of this class can be accessed as a collection. Current returns the same element until MoveNext is called.
IEnumerable Returns the IEnumerator interface for a given object. IEnumerator Enables foreach style iteration of subtypes.
As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With