IEnumerable and Recursion using yield return

I have an IEnumerable<T> method that I’m using to find controls in a WebForms page.

The method is recursive and I’m having some problems returning the type I want when the yield return is returnig the value of the recursive call.

My code looks as follows:

public static IEnumerable<Control> GetDeepControlsByType<T>(this Control control)
{
    foreach(Control c in control.Controls)
    {
        if (c is T)
        {
            yield return c;
        }

        if(c.Controls.Count > 0)
        {
            yield return c.GetDeepControlsByType<T>();
        }
    }
}

This currently throws a “Cannot convert expression type” error. If however this method returns type IEnumerable<Object>, the code builds, but the wrong type is returned in the output.

Is there a way of using yield return whilst also using recursion?

8 Answers
8

Leave a Comment