[RESOLVED] C# Create generic class from variable objecttype
I have the following working code
Main.cs
Code:
Bootstrap<ROC> boot = new Bootstrap<ROC>(selectedTool as ROC);
Bootstrap.cs
Code:
class Bootstrap<T> where T : class, IBootstrappable {
DataTable data;
public Bootstrap(T selectedTool) {
data = selectedTool.CreateBootstrapDataTable();
}
Tools.cs
Code:
public interface IBootstrappable {
DataTable CreateBootstrapDataTable();
}
selectedTool has type ROC in this case, which is a derived class from StatisticalTool. However, the application should work for other derived classes as well.
So I need something like
Code:
Type type = selectedTool.GetType();
Bootstrap<type> b = new Bootstrap<type>(selectedTool as type);
But this doesn't work. Who has the solution?
Re: C# Create generic class from variable objecttype
Generics are compile time entities. If you need dynamic creation of a certain type defined at runtime use reflection.
Re: C# Create generic class from variable objecttype
Yes. You need the Type.MakeGenericType() method.