Search code examples
c#reflectionstrong-typing

use a type object with strongly typed methods


I'm not even sure if this would be possible, but here is the problem I'm facing.

Basically I have a strongly typed methods as follow

ConsoleHelper.Start<T>() where T:IService

What I would like to achieve is to dynamically load T using reflection, so something along the line of

var type = Assembly.Load("assembly").GetType("type");

then use that type with the strongly typed method defined above. Is this at all possible?


Solution

  • Sure, you can use MethodInfo.MakeGenericMethod to do this.

    var startMethod = typeof(ConsoleHelper).GetMethod("Start");
    
    // Equivalent of Start<SomeType>
    var typedStartMethod = startMethod.MakeGenericMethod(typeof(SomeType));