Abstract class with constructor, force inherited class to call it

c#

Solution

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.

Problem

I have an `abstract` class with constructor `XYZ(string name)`. Also I have a class that inherits from that abstract class. How to force inherited class to call `base(string name)`? Now I can use `new Inherited()` and it will not call base constructor. I want to force user to implement default constructor in inherited class.

Original source