0

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);
cmd.prompt
  • 954
  • 7
  • 14
  • 2
    The first part of the answer should help: http://stackoverflow.com/questions/253937/recursive-control-search-with-linq – Jan Aug 23 '12 at 01:10
  • 1
    The second part is equally relevant. Once you have all controls, use `OfType()` to get the ones you're after. – Jay Aug 23 '12 at 01:17

1 Answers1

2

The "magic" is simply declaring another method that returns the List<T> rather than void.

List<T> GetAllControlsOfType<T>(Control parent) where T : class {
    List<T> list = new List<T>();
    GetAllControlsoFType<T>(list, parent);   // Invoke your existing method
    return list;
}

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:

    if (parent.GetType() == typeof(T))
    

    But it would be more clear to write it as:

    if (parent is T)
    

    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 parent declared as this Control parent (provided it's declared in a static class)

    This would allow you to invoke the method as this.GetAllControlsOfType<WebControl>()

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195