Search code examples
c#inheritanceoptional-arguments

Inheriting constructor with single optional argument


I have a set of classes that inherit from a base...

public abstract class BaseClass
{
    public BaseClass()
    {
        // ...
    }
}

public abstract class BaseMessageClass : BaseClass
{
    // ...
}

public SpecificMessageClass : BaseMessageClass
{
   // ...
}

Instantiating an object like this works:

SpecificMessageClass myMessage = new SpecificMessageClass();

However, I need to change all constructors to have an optional string parameter, like this:

public abstract class BaseClass
{
    public BaseClass(string optParam="whatever")
    {
        // ...
    }
}

Now, when I try and instantiate the object with the optional argument:

SpecificMessageClass myMessage = new SpecificMessageClass("coolstring");

I get the error:

'SpecificMessageClass' does not contain a constructor that takes 1 arguments"

Is there ANY way to do this without explicitly declaring the constructors in each level of inherited class?


Solution

  • No.

    But given that you want to inherit, I'm guessing you want the same logic to apply at all levels on some inherited field or property. If so, the closest you can get is to add a factory method like a Create<T>(string optParam="whatever") on the base class like the following:

    public class BaseClass
    {
        public static T Create<T>(string optParam="whatever") where T : BaseClass
        {
            var t = new T(); //which invokes the paramterless constructor
            ((BaseClass)t).SomePropertyOrFieldInheritedFromTheBaseClass = optParam; //and then modifies the object however your BaseClass constructor was going to.
            return t;
        }
    }
    

    That would allow all implementers of the class to implement the BaseClass and get the same effect as having the optional parameter constructor.

    By the way, I didn't test the above code, so you might need to tweak it slightly. But hopefully it gives the idea.

    I think that's probably the closest you can get.