class TypeWriter
{
public void WriteType<T>(TextWriter target)
{
target.WriteLine("T is {0}", typeof(T));
}
}
This generic method needs to be called with its type parameter resolved at runtime, like this:{
public void WriteType<T>(TextWriter target)
{
target.WriteLine("T is {0}", typeof(T));
}
}
var typeWriter = new TypeWriter();
typeWriter.WriteType<Program>(Console.Out);
which gives this output:typeWriter.WriteType<Program>(Console.Out);
foreach (var assemblyType in Assembly.GetExecutingAssembly().GetTypes())
{
// typeWriter.WriteType<assemblyType>(Console.Out);
}
{
// typeWriter.WriteType<assemblyType>(Console.Out);
}
This is where System.Reflection comes in. The MethodInfo class has a method MakeGenericMethod that takes an array of System.Type, substitutes the method's generic parameters for the arguments and returns a new MethodInfo instance. This new MethodInfo instance can then be invoked like any other. Here's how this looks in code:
foreach (var assemblyType in Assembly.GetExecutingAssembly().GetTypes())
{
// Get a handle on the method to call
var method = typeof(TypeWriter).GetMethod("WriteType");
// Pass the type parameter(s)
var genericMethod = method.MakeGenericMethod(assemblyType);
// Call the method on the TypeWriter instance, passing parameter(s)
genericMethod.Invoke(typeWriter, new[] { Console.Out });
}
This gives the output:{
// Get a handle on the method to call
var method = typeof(TypeWriter).GetMethod("WriteType");
// Pass the type parameter(s)
var genericMethod = method.MakeGenericMethod(assemblyType);
// Call the method on the TypeWriter instance, passing parameter(s)
genericMethod.Invoke(typeWriter, new[] { Console.Out });
}