Abstract class with constructor, force inherited class to call it

A class without an explicit constructor has a parameterless constructor. In the other hand, if you implement a constructor with parameters and no paramterless constructor, your class won't be instantiable without arguments.

In other words:

public abstract class A 
{
    public A(string x) 
    {
    }
}

public class B : A 
{
    // If you don't add ": base(x)" 
    // your code won't compile, because A has a 
    // constructor with parameters!
    public B(string x) : base(x)
    {
    }
}

That is, if A has a parameterless constructor (or no explicit constructor), B will automatically call the base constructor. You don't need to code any further stuff here.

Otherwise, if your base class has a parameterless constructor and a constructor with parameters, you can't force a derived class to automatically call a constructor excepting the default one (i.e. the so-called parameterless constructor).

Workaround

Well, there's no special workaround here, but be aware C# supports optional parameters in both constructors and methods.

If you want to be 100% sure derived classes will call a concrete base constructor, you can implement your base class using a single parameterless constructor with optional parameters and use this instead of constructor overloading:

public class A
{
    public A(string x = "hello world") // or just string x = null
    {

    }
}

Now if a B class derived A, B will always call A's base constructor, since x is optional and it has a default value.


How to force inherited class to call base(string name)

Make parameterless constructor in your abstract class private, or not add it at all. That's will force all derived classes to call the constructor you specified or there will be a compile error.

public abstract class BaseClass
{
    protected BaseClass(string parameter)
    {
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
    }
}

Will end up with

'`Project.BaseClass`' does not contain a constructor that takes 0 arguments

Tags:

C#