Search code examples
c#genericsruntimeactivator

C# Create objects with Generics at runtime


In the following example i can create an object dynamically via a string; however, i have no way to get at the public methods of BASE class. i can't cast obj to a BASE because i don't know what generic will be used at design time. any suggestings on doing so at runtime would be nice.

Project A contains Class A{T,J> : BASE{T,J>
Project B contains Class B{T,J> : BASE{T,J>

Project C contains Class BASE{T,J>
public virtual control{T,J> item

Project Windows Form
cmdGo_Click event

string dll = textbox1.text //ex "ProjectA.dll"
string class = textbox2.text //ex "A`2[enuT,enuJ]"
object obj = activator.createinstancefrom(dll,class)


Solution

  • At runtime the generics part of the equation does not matter, because the compiler has already filled in the gaps for the generic implementation. I believe you can use reflection to get at the base class methods, like in this example below, I hope this helps.

    MethodInfo[] baseMethods = obj.GetType().BaseType.GetMethods();
    object retObj = baseMethods[0].Invoke(obj, new object[] {"paramVal1", 3, "paramVal3"});