tinymarsracing
tinymarsracing

Reputation: 657

Can I re-use my superclass's optional constructor parameter in my subclass?

I have a superclass with a constructor using an optional parameter to avoid writing multiple overloaded constructors:

namespace Example
{
    abstract class Super
    {
        string mandatory;
        string optional;
        const string optionalDef = "default";

        public Super(string mandatory, string optional = optionalDef)
        {
            this.mandatory = mandatory;
            this.optional = optional;
        }
    }
}

The constructor can be called with one or two arguments, so it's like I'm implementing two overloaded constructors. Now I'm trying to "re-use" this in a subclass:

namespace Example
{
    class Sub : Super
    {
        public Sub(string mandatory, string optional) : base(mandatory, optional) { }

        public Sub(string mandatory) : base(mandatory) { }
    }
}

Since my default value is "hidden" in the superclass, I don't know how to mirror my structure from the superclass that avoids the overloaded constructors. I wanna do something like this which of course doesn't exist:

public Sub(string mandatory, string optional = undefined) : base(mandatory, optional) { }

Another thing I've tried is this:

public Sub(string mandatory, string optional = base.optionalDef) : base(mandatory, optional) { }

I think this might work if I make optionalDef static (which seems like a hack), but as soon as I subclass Sub again, it won't work anymore I think (since base.base isn't allowed).

Thank you!

Upvotes: 0

Views: 121

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460350

You can simply make optionalDef protected:

abstract class Super
{
    string mandatory;
    string optional;
    protected const string optionalDef = "default";

    public Super(string mandatory, string optional = optionalDef)
    {
        this.mandatory = mandatory;
        this.optional = optional;
    }
}

abstract class Sub : Super
{
    public Sub(string mandatory, string optional = optionalDef) : base(mandatory, optional) { }
}

If that's not possible for whatever reason and null is not a possible value, you could also use that.

Upvotes: 1

Related Questions