tags:

views:

1497

answers:

3

If it harder to explain using words, let's look at an example I have a generic function like this

void FunctionA<T>() where T : Form, new()
{
}

If I have a reflected type, how do I use it with the above function? I'm looking forward to do this

Type a = Type.GetType("System.Windows.Forms.Form");
FunctionA<a>();

Of cause the above method doesn't working.

+4  A: 

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... he's a dick, but he's 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.

Will
How can .NET get so close to the power of a 1958 technology and yet still be so far away?
Bryan Anderson
.NET is mainstream, Lisp (I assume that's what your reference is to) is not. That may answer the "why" question.
Pavel Minaev
That's one very definitive answer. Too bad it's incorrect. You can, through reflection, invoke generic methods using generic arguments resolved at runtime. It's not always desired, and one may wonder why he has to do it before actually using it, but it's possible.
Jb Evain
I hate you, Jb. I hate you so much.
Will
+3  A: 

Actually, this is not correct. Generic types can be instantiated at run-time in .NET.

Use MethodInfo.MakeGenericMethod

Frank
A: 

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

devi