Check for implementation of an Interface recursively, c#
c#, interface, recursion, reflection
Solution
I think you need to split this method into 2 parts
- Find Controls recursively
- Find Controls implementing the interface based off of #1
Here is #1
public static IEnumerable<Control> FindAllControls(this Control control) {
yield return control;
foreach ( var child in control.Controls ) {
foreach ( var all in child.FindAllControls() ) {
yield return all;
}
}
}
Now to get all controls of a type, use the OfType extension method
var all = someControl.FindAllControls().OfType<ISomeInterface>();
Problem
I have a situation in a WebForm where I need to recurse throguh the control tree to find all controls that implement a given interface. How would I do this? I have tried writing an extension method like this ``` public static class ControlExtensions { public static List<T> FindControlsByInterface<T>(this Control control) { List<T> retval = new List<T>(); if (control.GetType() == typeof(T)) retval.Add((T)control); foreach (Control c in control.Controls) { retval.AddRange(c.FindControlsByInterface<T>()); } return retval; } } ``` But it does not like the cast to `T` on line 7. I also thought about trying the as operator but that doesn't work with interfaces. I saw Scott Hanselmans disucssion but could not glean anything useful from it. Can anyone give me any pointers. Thanks. Greg