Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a method returning IEnumerator<T> and use it in a foreach loop?

Tags:

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?

like image 258
littlecharva Avatar asked Aug 06 '08 12:08

littlecharva


People also ask

Is IEnumerator a return type?

IEnumerable is the return type from an iterator. An iterator is a method that uses the yield return keywords.

What must an object implement to use a for each loop?

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 .

How to use IEnumerator in c#?

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.

Which of the following interface enables foreach style iteration over generic collections?

IEnumerable Returns the IEnumerator interface for a given object. IEnumerator Enables foreach style iteration of subtypes.


1 Answers

As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.

like image 192
David Wengier Avatar answered Sep 19 '22 15:09

David Wengier