I have a method that returns a List<T> of child controls that looks like this:
void GetAllControlsOfType<T>(List<T> lst, Control parent) where T:class
{
if (parent.GetType() == typeof(T))
lst.Add(parent as T);
foreach (Control ch in parent.Controls)
this.GetAllControlsOfType<T>(lst, ch);
}
But I have to use it like this:
List<WebControl> foo = new List<WebControl>();
GetAllControlsOfType<WebControl>(foo, this); //this = webpage instance
Surely there is some c# magic that will allow me to write a method that I can call like this:
List<WebControl> foo = GetAllControlsOfType<WebControl>(this);
The “magic” is simply declaring another method that returns the
List<T>rather thanvoid.Because you’re using recursion, you can’t simply modify your existing method to return
List<T>, since doing so would make it impossible for you to keep track of that list and build on it.A few other minor points:
You have:
But it would be more clear to write it as:
Unless, of course, you truly want your method to fail when used with subclasses of
T.You may want to consider declaring the new method as an extension method by making
parentdeclared asthis Control parent(provided it’s declared in a static class)This would allow you to invoke the method as
this.GetAllControlsOfType<WebControl>()