I have an IEnumerable 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
GetDeepControlsByType(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();
}
}
}
This currently throws a "Cannot convert expression type" error. If however this method returns type IEnumerable, the code builds, but the wrong type is returned in the output.
Is there a way of using yield return whilst also using recursion?
Answer
Inside a method that returns IEnumerable, yield return has to return T, not an IEnumerable.
Replace
yield return c.GetDeepControlsByType();
with:
foreach (var x in c.GetDeepControlsByType())
{
yield return x;
}
No comments:
Post a Comment