Odys Odys - 11 months ago 43
C# Question

Can I force descendants to have a parameterless constructor?

I am trying to create a generic factory-pattern-like mechanism.

The factory will be like:

public class APlugin<ActionType> where ActionType : IAction
// create a new action. Note: ActionType should contain
// an empty constructor
public ActionType CreateAction()
return Activator.CreateInstance<ActionType>();

Descendants of IAction might hide the parameterless constructor and this will cause the factory to fail.

Answer Source

You can't force an empty constructor or any type of constructor on derived types.

Constructors do not get inherited, but do get called.

If not chaining to the base constructor (using the : base() syntax), the default base constructor will be called implicitly.

From Using Constructors on MSDN:

In a derived class, if a base-class constructor is not called explicitly using the base keyword, then the default constructor, if there is one, is called implicitly.