How to use typeof or GetType() as Generic's Template?

class Program
{
    static void Main(string[] args)
    {
        int s = 38;


        var t = typeof(Foo);
        var m = t.GetMethod("Bar");
        var g = m.MakeGenericMethod(s.GetType());
        var foo = new Foo();
        g.Invoke(foo, null);
        Console.ReadLine();
    }
}

public class Foo
{
    public void Bar<T>()
    {
        Console.WriteLine(typeof(T).ToString());
    }
}

it works dynamicaly and s can be of any type


You can't. Generics in .NET must be resolved at compile time. You're trying to do something that would resolve them at runtime.

The only thing you can do is to provide an overload for FunctionA that takes a type object.


Hmmm... the commenter is right.

class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Foo);
        var m = t.GetMethod("Bar");
        var hurr = m.MakeGenericMethod(typeof(string));
        var foo = new Foo();
        hurr.Invoke(foo, new string[]{"lol"});
        Console.ReadLine();
    }
}

public class Foo
{
    public void Bar<T>(T instance)
    {
        Console.WriteLine("called " + instance);
    }
}

MakeGenericMethod.


A few years late and from a msdn blog, but this might help:

Type t = typeof(Customer);  
IList list = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(t)));  
Console.WriteLine(list.GetType().FullName); 

Tags:

.Net

Generics