C# Create objects with Generics at runtime
Question
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"});
OTHER TIPS
This code creates an instance of BASE<int, string> :
Type type = typeof(BASE<,>).MakeGenericType(typeof(int), typeof(string));
object instance = Activator.CreateInstance(type);
If you do not know the type parameters used at run-time, then you cannot use any operations that depend on these types either, so... why not make a non-generic base class to BASE
that contains all the operations that do not depend on the generic parameters, then you can case obj
to that base type and use it.