Create instance of generic type whose constructor requires a parameter?

Boris Callens picture Boris Callens · Apr 8, 2009 · Viewed 233.6k times · Source

If BaseFruit has a constructor that accepts an int weight, can I instantiate a piece of fruit in a generic method like this?

public void AddFruit<T>()where T: BaseFruit{
    BaseFruit fruit = new T(weight); /*new Apple(150);*/
    fruit.Enlist(fruitManager);
}

An example is added behind comments. It seems I can only do this if I give BaseFruit a parameterless constructor and then fill in everything through member variables. In my real code (not about fruit) this is rather impractical.

-Update-
So it seems it can't be solved by constraints in any way then. From the answers there are three candidate solutions:

  • Factory Pattern
  • Reflection
  • Activator

I tend to think reflection is the least clean one, but I can't decide between the other two.

Answer

meandmycode picture meandmycode · Apr 8, 2009

Additionally a simpler example:

return (T)Activator.CreateInstance(typeof(T), new object[] { weight });

Note that using the new() constraint on T is only to make the compiler check for a public parameterless constructor at compile time, the actual code used to create the type is the Activator class.

You will need to ensure yourself regarding the specific constructor existing, and this kind of requirement may be a code smell (or rather something you should just try to avoid in the current version on c#).