Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My first generic casting (C#)

Tags:

c#

generics

I was all excited at writing this generic function when the compiler threw an error (unable to cast T to System.Web.UI.Control)

I basically pass it a type when I call it, and it look for all controls of that type. The error occurs on l.Add((T)ctrl);

    private List<T> RecurseTypes<T>(Control ctrls)
    {
        var l = new List<T>();
        foreach (var ctrl in ctrls.Controls)
            if (ctrl.GetType() is T)
                l.Add((T)ctrl);
        return l;
    }

Am I missing something or am I just out of luck?

like image 523
maxp Avatar asked Jan 24 '11 13:01

maxp


1 Answers

private List<T> RecurseTypes<T>(Control parent) where T: Control
{
    var l = new List<T>();
    foreach (var child in parent.Controls)
        if (child is T)
            l.Add((T)child);
    return l;
}

2 changes:

  • add a where T : Control generic constraint
  • see the is usage (the control can be a T, but GetType() returns Type, which is never a Control)

Also, note that this doesn't really recurse; this could just be:

return ctrl.Controls.OfType<T>().ToList();
like image 123
Marc Gravell Avatar answered Nov 18 '22 00:11

Marc Gravell