Search code examples
c#asp.net-core-2.0system.reflection

How to set the T of a method from object type property?


I want to be able to use a T type variable from a class that hold the types as properties. How do I do that dynamically?

I got this type:

public class Mapper 
{
    public string Key {get; set;}
    public Type RequestType {get; set;}
    public Type ResponseType {get; set;}

    public Mapper(string key) 
    {
        RequestType = typeof(SomeType);
        ResponseType = typeof(SomeType2);
    }
}

And I got this class

public class Handler<T> where T: new () 
{
  // some properties and methods
}

I wish to do the following:

var mapper = new Mapper("Key1");
Hanadler<mapper.RequestType> handler = new Handler<mapper.RequestType>();

The issue i always get is:

'mapper' is a variable but is used like a type

I tried to look for such examples all over the web but im not even sure how to describe this.

Please note its different from the Duplicate proposal, as this is relevant for creating new instance of an object while the other answer is about generating generic method. The duplicate proposal was actually helpful to continue after this answer using the new instance dynamically created.

Any help will be appreciated


Solution

  • Because you have to use Type in generic position and you have to determine your target type in compile time;

    Hanadler<TargetType> handler = new Handler<TargetType>();
    

    If you want to determine the target generic type in Runtime, you have to use reflection. In your case:

    var d1 = typeof(Handler<>);
    Type[] typeArgs = { mapper.RequestType };
    var makeme = d1.MakeGenericType(typeArgs);
    object o = Activator.CreateInstance(makeme);
    

    You can see the MSDN documentation here:
    https://msdn.microsoft.com/en-us/library/system.type.makegenerictype(v=vs.110).aspx