Following code doesn’t compile:
class GenericFactory where T : new()
{
public T Create(object a, object b)
{
return new T(a, b);
}
}
The compiler will give you following error message: “‘T’: cannot provide arguments when creating an instance of a variable type.”. Well, there are a couple ways to solve this issue.
Use reflection
class GenericFactory
{
public T Create(object a, object b)
{
return (T) typeof(T).GetConstructor(
new System.Type[] { typeof(object), typeof(object) }).Invoke(new object[] {a, b});
}
}
Use intialization
Following code uses an initialization interface to solve this issue. You can also use properties instead of a method.
interface I
{
void Initialize(object a, object b);
}
class GenericFactory where T : I, new()
{
public T Create(object a, object b)
{
T t = new T();
t.Initialize(a, b);
return t;
}
}