26

Is it possible to enforce a compile-time contract on derived classes requiring implementation of a constructor (with parameter)?

I have a base class with a constructor requiring a parameter:

public class FooBase
{
  protected int value;
  public FooBase(int value) { this.value = value; }
  public virtual void DoSomething() { throw new NotImplementedException(); }
}

I'd like to force derivations of my base class to implement the same constructor:

public class Foo : FooBase
{
  public Foo(int value) : base(value) { }
  public override void DoSomething() { Console.WriteLine("Foo: {0}", value); }
}

If no constructor is implemented, derived classes causes a compiler error because there is no default constructor in the base class:

// ERROR: 'Does not contain a constructor that takes 0 arguments'
// Adding default constructor in FooBase eliminates this compiler error, but
// provides a means to instantiate the class without initializing the int value.
public class FooBar : FooBase
{
  public override void DoSomething() { Console.WriteLine("FooBar: {0}", value); }
}

Adding a default constructor, FooBar(), in the derived class silences the compiler error, but provides a dangerous means of instantiating FooBar without the required base class int value being initialized. Because I'm using a factory (see below), silencing the compiler error only results in a run-time error later. I'd like to force FooBar to implement FooBar(int)

INTERESTING OBSERVATION:

If a default constructor, FooBase(), is added to FooBase, then it is 'inherited' by derived classes that do not provide a constructor:

  1. Foo does not inherit the default constructor because it supplies an explicit constructor.
  2. FooBar DOES inherit FooBase().

HOWEVER, the same is not true with the non-default constructor FooBase(int)!

  1. Foo MUST explicitly implement FooBase(int) and call base(int).
  2. FooBar FAILS to 'inherit' the non-default constructor the same way that a default constructor is inherited!

I do not want a default constructor in the base class because instances are created using a factory method that supplies a needed "settings" parameter. That factory method is not illustrated here (which uses the Activator.CreateInstance() method).

Here is the way derived classes should be instantiated:

  static void Main(string[] args)
  {
    FooBase myFoo = new Foo(4);     // Works, since Foo(int) is implemented.

    // ERROR: 'Does not contain a constructor that takes 1 arguments'
    FooBase myFooBar = new FooBar(9);  // Fails to compile.
  }

Because I am using a factory--not direct instantiation as shown--there is no compiler error. Instead, I get a runtime exception: 'Constructor on type not found.'

Unworkable solutions:

  • Interfaces do not support constructors.
  • Constructors cannot be virtual or abstract.

It appears that supplying a base class cannot enforce a contract on constructors.

Work-around:

  • Provide a default constructor in base class along with property to pass settings parameter.
2
  • THE REAL PROBLEM: How to enforce that the constructor signature "ctor(int)" is implemented in derived classes? This is the constructor my factory method expects. EXAMPLE: If FooBar implements "FooBar() : base(5)" then there is no compile time error since a constructor is provided. However, my factory method looks for FooBar(int) and thus a run-time error will occur. SOLUTION: It appears BrokenGlass has helped identify a better pattern--implement an Init(int) method in the base class (not interface) since enforcing a particular constructor signature does not seem possible. Jul 2, 2011 at 22:22
  • FINAL SOLUTION: I chose to implement a base class property to accept the "setting" needed by the instantiated classes: public SettingType Setting (in reality I'm not passing an int). ZERO burden is placed upon derived class implementers since the implementation is entirely within the base class. @BrokenGlass suggested adding a method like Init(SettingType setting), however, a property seems more appropriate since an Init() method would require a protected backing field where a property already does this. Also, methods should perform actions (verbs) and properties accept values. Jul 2, 2011 at 23:08

5 Answers 5

11

If a default constructor, FooBase(), is added to FooBase, then it is 'inherited' by derived classes that do not provide a constructor:

This is incorrect - constructors in general are never inherited. A default constructor is automatically provided for a class that does not provide any other constructor implementation.

You could put in a constraint on an interface that provides an Init() method for you:

public interface IInit
{
   void Init(int someValue);
}

public class FooBase : IInit
{
   ..
}
6
  • 1
    CORRECT. Which is why I put single-quotes around 'inherit', with the intent to denote it as a bad use of the term. The effect is that the base constructor is available to the derived class, whereas a non-default constructor is not available to a derived class. Jul 2, 2011 at 21:29
  • @Kevin: Ah, I missed that - sorry. In general constructor constraints are not possible currently. How about requiring an interface that implements an Init(int val) method? Jul 2, 2011 at 21:30
  • I think you're hitting on the only answer to the problem. I think the base class can implement Init(arg) or a parameter without requiring an interface. I'd prefer inheriting the base class to be enough (not base class AND interface). Also, the base class can handle the init--the derived class doesn't need to be involved. Jul 2, 2011 at 21:44
  • BEST ANSWER. Will implement a method or property similar to "Init(arg)" in my base class. I will not add an interface because the base class can enforce the new method/property. If I were defining an interface (not a base class), then I would require "Init(arg)" in the interface. Much thanks, BG! Jul 2, 2011 at 22:26
  • 1
    I ended up with this solution as well when I used reflection to get all the intherited classes of a base class (or interface) and I would like to create them by Activator.CreateInstance. However, this dropped the constructor-really-constructs principle to the trashbin because all the datas necessary to work passed to inherited classes AFTER creation; so compiler cannot be sure that objects were initialized properly. Designers of C# language should take this problem into view.
    – Feri
    Jan 28, 2018 at 13:56
10

Did you try

public class FooBase
{
  protected int value;
  private FooBase(){}
  public FooBase(int value) { this.value = value; }
  public virtual void DoSomething() { throw new NotImplementedException(); }
}

the private constructor prevents the option of parameter-less constructor

3
  • That's a huge improvement. (DUH, I feel stupid!) It does force the derived class implementer to at least call the correct base class constructor. HOWEVER, it does not guarantee the constructor signature needed for my factory method. Jul 2, 2011 at 21:39
  • You happened to illuminate an error on my part that I did not include in my example code. I did, in fact, provide a default constructor in my base class to silence compiler errors. However, the correct solution is not to make it "private"--it should simply be eliminated! Since FooBase(int) exists no implicit default constructor is provided. This is as it should be since I always want "value" to be initialized. Jul 2, 2011 at 22:16
  • 1
    THE REAL PROBLEM: How to enforce that the constructor signature "ctor(int)" is implemented in derived classes? This is the constructor that my factory method expects. An example: If FooBar implements "FooBar() : base(5)" then there is no compile time error since a constructor is provided. However, my factory method looks for FooBar(int) and thus a run-time error will occur. SOLUTION: It appears BrokenGlass has helped identify a better pattern--implement an Init(int) method in the base class since enforcing a particular constructor signature does not seem possible. THANKS for your contribution! Jul 2, 2011 at 22:20
3

If you provide just the constructor with a parameter on the base class, the derived class has to call that when it is constructed. This doesn't however force it how it should be called. It could be called with some default value, or the value could be computed from other constructor parameters.

Constructors are not inherited. What happens instead is that when you don't specify any constructors in a class (structs act differently), a public parameterless constructor is created, that calls the parameterless constructor of the base class. Of course, this won't happen if the base class doesn't have such constructor, in which case you have to specify the constructor yourself.

As @BrokenGlass mentions, the only way to force such a constraint is to have an abstract method Init() on the base class (possibly from an interface). I think that in general, such practice is not good OOP-design (object should be usable after creation, without the need to call other methods), but in this case it might be the best solution.

1
  • Since I am using a static factory method in the base class to create derived instances there is no compile-time constructor call to ctor(int); hence, there is no compiler error if a derived class instead implements ctor(string). Implementing Init(int) in the base class (not interface) ensures that derived classes will "plug in" to my consuming code without a run-time failure. Because Init(int) is in the base class, the derived class implementer bears no burden. Further, your good point about OOP instant usability is satisfied because these are "plug in" classes consumed only by my code. Jul 2, 2011 at 22:52
2

It seems either that I don't understand what you mean or what you mean is wrong.

Having the following, causes compiler error:

public class FooBase
{
    protected int value;
    public FooBase(int value) { this.value = value; }
    public virtual void DoSomething() { throw new NotImplementedException(); }
}
public class Foo : FooBase
{
    public Foo(int value) : base(value) { }
    public override void DoSomething() { Console.WriteLine("Foo: {0}", value); }
}

public class FooBar : FooBase
{
    public FooBar() // <----------------- HERE telling 'Test.FooBase' does not contain a constructor that takes 0 arguments
    {
    }

    public override void DoSomething() { Console.WriteLine("FooBar: {0}", value); }
}

So it is safe. But if you try to do the following

public class FooBase
{
    protected int value;
    public FooBase() {} // <------------ LOOK HERE
    public FooBase(int value) { this.value = value; }
    public virtual void DoSomething() { throw new NotImplementedException(); }
}
public class Foo : FooBase
{
    public Foo(int value) : base(value) { }
    public override void DoSomething() { Console.WriteLine("Foo: {0}", value); }
}

public class FooBar : FooBase
{
    public FooBar() // <----------------- No error here
    {
    }

    public override void DoSomething() { Console.WriteLine("FooBar: {0}", value); }
}

And if it is wrong to declare ctor in FooBase then it's your responsibility as a developer not to do so...

7
  • All the feedback is helping me understand the issue better. The core issue is enforcing that a particular constructor signature will be available at run-time for my factory method. In my example, this signature is Foo(int). But if FooBar instead implements "FooBar(string) : base(5) {}" then there is no compiler error but there is still a run-time error when the factory method looks for FooBar(int). Jul 2, 2011 at 22:09
  • In my opinion you should concentrate on making FooBase "reliable" when your FooBase will be reliable, it will be reliable i.e "safe" to derive it. Access modifiers "public/private/protected/internal/..." just create so called layers of access and actually there is no difference what level is leaking reliability. If class allows person to shoot himself in the leg then it is not reliable class, locate non-reliable constructs and replace them with reliable.
    – Lu4
    Jul 2, 2011 at 22:57
  • As an example consider protected int value; first you open access to this variable for derived classes and then think "what if somebody will gain that acces..." this is wrong from start... You shouldn't provide (open access) to members that might be non-operational at some moment of time. The rule of thumb is to provide access to members that are functional at any moment of time...
    – Lu4
    Jul 2, 2011 at 22:58
  • Thanks for your good comments on reliability. I agree. Final solution (see above) is a public property. In regards to visibility (public/protected/private) on that property, it must have a public setter available to the factory method--this is where a constructor would be better as it enforces a "one time only" write access. For real production, write-once logic might be added to the property. A protected (or more visible) getter must exist since it is the derived classes that use the value (the base class is not intended to be instantiated similar to System.Net.WebRequest.) Jul 2, 2011 at 23:22
  • You bring up good points that illustrate why a constructor (write-once) is safer than a property--which is why I tried to implement passing initialization settings in a constructor in the first place. I wonder if you have ideas on a more theoretically "perfect" solution? I can ensure the settings are passed because it is my code that consumes the derived "plug-in" classes. But in theory, by error or malice, the settings could be forgotten or tampered with... maybe a "copy-constructor" so instances can only be obtained via a properly initialized base class? Jul 2, 2011 at 23:30
1

As others have noted, an interface method such as Init() is a bit awkward. An interface should expose behavior, not internal requirements. The internal state of your object helps implement that behavior. A class is generally a way to wrap up state and behavior. The constructor exposes the internal requirements, but the consumer of the interface's "service" doesn't care about this; they only care about the behavior:

interface IFoo 
{
    void DoSomething();
}

So it's natural that different implementations will require different constructors because they often require different internal state to implement IFoo.DoSomething.

The problem that you're running into then is how to write general-purpose code that knows how to instantiate all of these different types. Factory methods and variations on Activator.CreateInstance are commonly used to accomplish this in an ad hoc manner. I'd encourage looking at a couple of alternatives that solve this more elegantly:

  • IoC/DI containers are generally a better approach because they standardize these techniques, perform better, and bring a lot of additional capabilities.
  • In .NET 4, the Managed Extensibility Framework (MEF, a.k.a. System.ComponentModel.Composition) has an overlapping set of capabilities with a lot of the same benefits, especially suited for plugin designs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.