tags:

views:

85

answers:

4

My first question is, is it possible to specify a generic type as a parameter, secondly, is anything such as the pseudo code ive listed below possible?

I assume it will be using .net 4.0 and the dynamics modifier but i am more interested in a pre 4.0 solution.

    public static void SomeMethod(List<T> l, Type type, Control samplecontrol)
    {
     l.Add((type)samplecontrol);
    }

Edit:

Here is my solution...

    public static void FindControlRecursive<T>(Control parent, List<T> l)
    {
        foreach (var ctrl in parent.Controls)
        {
            if (ctrl.GetType() == typeof(T))
                l.Add((T)ctrl);
            if (((Control)ctrl).Controls != null && ((Control)ctrl).Controls.Count > 0)
                foreach (Control _ctrl in ((Control)ctrl).Controls)
                    FindControlRecursive<T>(_ctrl, l);
        }
    }
+4  A: 

You mean this?

public static void SomeMethod<T>(List<T> l, T item)
{
    l.Add(item);
}
Paul Ruane
+1  A: 

Try this

public static void YourMethodName<T>(List<T> l, Control samplecontrol)
{
    l.Add((T)samplecontrol);
}
RaYell
+1  A: 

Yes, it is possible, and has been since C# 2.0. This is probably the syntax you are looking for:

public static void AddControlToList<T>(List<T> list, Control sampleControl)
{
    list.Add((T)sampleControl)
}
driis
+2  A: 

You need to add the generic type modified to the method name. That will replace your type parameter that you were trying to pass in,

public static Add<T>(List<T> l, T samplecontrol)
{
 l.Add(samplecontrol);
}

You can also add type qualifiers onto the method

public static Add<T>(List<T> l, T samplecontrol) 
    where T : Control
{
 l.Add(samplecontrol);
}
Bob