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.
Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new .
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.
Pretty late but i think this is worth knowing..
You can force constructors with 0 parameters on non-abstract classes. This is a type constraint to use whenever you want to enforce those constraints on a class structure. It requires you to specify the type that implements the interface which might be found disturbing. That's the price if you want some neat type safety.
public interface IEmptyConstructor<TThis> where TThis : IEmptyConstructor<TThis>, new() {}
for example a singleton structure
public abstract class Singleton<TThis> : ISingleton where TThis : Singleton<TThis>, new() { /* some singleton madness */ }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With