I want to create simple factory class which implements interface like this:
IFactory
{
TEntity CreateEmpty<TEntity>();
}
In this method I want to return an instance of type TEntity (generic type).
Example:
TestClass test = new Factory().CreateEmpty<TestClass>();
Is it possible? Does interface is correct?
I’ve tried something like this:
private TEntity CreateEmpty<TEntity>() {
var type = typeof(TEntity);
if(type.Name =="TestClass") {
return new TestClass();
}
else {
...
}
}
But it doesn’t compile.
You need to specify the
new()constraint on the generic type parameterThe new constraint specifies that the concrete type used must have a public default constructor, i.e. a constructor without parameters.
If you don’t specify any constructors at all, then the class will have a public default constructor by default.
You cannot declare parameters in the
new()constraint. If you need to pass parameters, you will have to declare a dedicated method for that purpose, e.g. by defining an appropriate interfaceIn your factory