Question

Code

public class Test
{
    public int id{get;set;}
    public Type test{get;set;}
}    

public object Convert<T1, T2>()
{ 
    //do stuff        
}

public void DoConvert()
{
    var a = Convert<Test, Test>(); // This Works

    var t = new Test() { test = typeof(Test); }
    var b = Convert<t.test, t.test>(); // This does not work!
}

Problem

As stated above in the code. How can I make the Convert method work where the T1 and T2 are defined at runtime?

Was it helpful?

Solution

You have to user reflection to obtain the result with Type.MakeGenericType. Assume Convert method is static and in Temp class:

class Temp
{
    public static object Convert<T1, T2>()
    { 
        //do stuff        
    }
}

Then you can call:

// assume code to get type1 and type2 dynamically
var type1 = GetGetType1();
var type2 = GetGetType2();

var method =  typeof(Temp).GetMethod("Convert")
                             .MakeGenericMethod(type1, type2);

method.Invoke(null, null);  //assume Convert is static method

OTHER TIPS

Type.MakeGenericType is your friend here. You cannot create generic types in runtime like that, you must use reflection. But then you will lose static type which is something you should be aware of.

How can I make the Convert method work where the T1 and T2 are defined at runtime?

Reflection or runtume code generation are your only options.

Templates in compiled code have to be resolved by the compiler. So either you create and compile code at runtime (the compiler is part of the runtime) as is done by ASP.NET; or you avoid compilation by using reflection (as the other answer notes: Type.MakeGenericType allows you to take MyType<> and a T to get MyType<T>).

For a generic method use MethodInfo.MakeGenericMethod

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top