3
Answers

How to specify type for generic class?

William Snell

William Snell

10y
891
1
I found some code online that allows me to find controls of a specific type recursively within a Control in ASP.NET Web Forms. It works great. Here's the code:

internal class ControlFinder<T> where T : Control
    {
        private readonly List<T> _foundControls = new List<T>();
        public List<T> FoundControls
        {
            get { return _foundControls; }
        }

        public List<T> FindControls(Control control)
        {
            foreach (Control childControl in control.Controls)
            {
                if (childControl.GetType() == typeof(T))
                    _foundControls.Add((T)childControl);
                else
                    FindControls(childControl);
            }

            return FoundControls;
        }
    }

It can be consumed like this:

var textboxes = new ControlFinder<TextBox>().FindControls(control);

This is exactly what I needed, but I found a need to be more fluid, and allow passing in the type rather than just using "TextBox". In my case, if the input controls needed to be disabled, I have this method:

public static void DisableTextBoxes(this Control control)
        {
            var controls = new ControlFinder<TextBox>().FindControls(control);

            foreach (var textbox in controls)
            {
                textbox.Text = "";
                textbox.Enabled = false;
            }
        }

As I said, this works great. But I'd like to write an extension method that allows passing in the type when called. The relevant code would be changed to this:

public static void DisableTextBoxes(this Control control, Type type)
        {
            var controls = new ControlFinder<type>().FindControls(control);

Problem is, this doesn't work. I get an error stating that the type or namespace couldn't be found. Is it not possible to initialize a generic class with a variable? 
Answers (3)