As Jared says, you can specify it in the code as you would for a static call:
using System; class Program { void Foo<T>() { Console.WriteLine(typeof(T)); } static void Main(string[] args) { dynamic p = new Program(); p.Foo<string>(); } }
The above code prints System.String .
Now, if you only know T at runtime, it's a little more complicated. If you have an instance, you can use dynamic typing and the output type together:
using System; class Program { void Foo<T>() { Console.WriteLine(typeof(T)); } static void Main(string[] args) { dynamic p = new Program(); dynamic v = GetRandomInstance();
EDIT: Paul came up with a great idea in the comments. You do not need to invent an instance of T , just an array. This means that you can even use type arguments in which you normally could not get an instance of T (for example, due to a private constructor):
using System; class PrivateConstructor { private PrivateConstructor() {} } class Program { static void Foo<T>() { Console.WriteLine(typeof(T)); } static void CallFooProxy<T>(T[] array) { Foo<T>(); } static void CallFoo(Type t) { dynamic array = Array.CreateInstance(t, 0); CallFooProxy(array); } static void Main(string[] args) { CallFoo(typeof(PrivateConstructor)); } }
Before anyone asks - no, this does not allow you to dynamically call Foo<Enumerable> - you still cannot use a static class as an argument of type, even if you try to postpone the attempt until runtime :)
If all this fails for some reason, it returns to reflection as usual ... get information about the method, call MakeGenericMethod and call it.
source share