Maximus Decimus Maximus Decimus - 4 months ago 15
C# Question

Recursive function to find user controls in a generic type

This is my code

private void FindControls<T>(Control control, List<T> list)
{
foreach (Control c in control.Controls)
{
if (c != null)
{
if (c is T)
{
list.Add(c); //<-- Problem is here
}
else
{
FindControls<T>(c, list);
}
}
}
}


I got the message


"The best overloaded match for
'System.Collection.Generic.List.Add(T)' has some invalid arguments"


This is another method to find the specific control

private void MyMethod(Employee e)
{
List<MyUserControlType> employees = new List<MyUserControlType>();
this.FindControls<MyUserControlType>(this.MyControlRoot, employees);
foreach (var employee in employees)
{
....
}
}


I want to return a list of controls of type MyUserControlType which doesn't inherit from type Control. Inherits from UserControl

How can I resolve this?

Answer

Well you can cast it using as operator like

            if (c is T)
            {
                list.Add((c as T));  //<-- Problem is here
            }

That constraint can be placed by modifying your method definition

private void FindControls<T>(Control control, List<T> list) where T : class
{

(OR) as pointed by @Ivan in comment you can cast it directly using the cast operator which won't require you to place the generic constraint

            if (c is T)
            {
                list.Add((T)c);  //<-- Problem is here
            }