title: Check for implementation of an Interface recursively, c#
body: <p>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.</p>
  
  <p>How would I do this?</p>
  
  <p>I have tried writing an extension method like this</p>
  
  <pre><code>public static class ControlExtensions
  {
      public static List&lt;T&gt; FindControlsByInterface&lt;T&gt;(this Control control)
      {
          List&lt;T&gt; retval = new List&lt;T&gt;();
          if (control.GetType() == typeof(T))                
              retval.Add((T)control);
  
  
          foreach (Control c in control.Controls)
          {
              retval.AddRange(c.FindControlsByInterface&lt;T&gt;());
          }
  
          return retval;
      }
  }
  </code></pre>
  
  <p>But it does not like the cast to <code>T</code> on line 7.
  I also thought about trying the as operator but that doesn't work with interfaces.</p>
  
  <p>I saw <a href="http://www.hanselman.com/blog/DoesATypeImplementAnInterface.aspx" rel="nofollow noreferrer">Scott Hanselmans disucssion</a> but could not glean anything useful from it.</p>
  
  <p>Can anyone give me any pointers. Thanks.</p>
  
  <p>Greg</p>