0

Let's say I have two classes Base and Derived : Base.

Derived shall be able to use a DerivedComponent : BaseComponent, just like all other derivates of Base use their own derivate specific component. All these BaseComponent components, like DerivedComponent, have some common functionality accessible in Base.

Since I don't want to downcast this BaseComponent every time I use DerivedComponent functionality in Derived, I also added its reference as DerivedComponent to Derived.

class Base
{
    private BaseComponent component;

    protected Component
    {
        get { return component; }
    }

    Base(BaseComponent component)
}

class Derived : Base
{
    private DerivedComponent component;

    Derived() : base(new DerivedComponent())
    {
        this.component = (DerivedComponent) base.Component;
    }
}

class BaseComponent {}

class DerivedComponent : BaseComponent {}

Is it necessary to do it this way, with the downcast? Can't I somehow reuse the argument from base() and assign it directly to my Derived's component?

  • Sorry, but "Questions asking for assistance in explaining, writing or debugging code are off-topic here". If you want to ask questions generally about inheritance, then they would be on topic. You could ask this question on Stack Overflow instead. Be warned that it'll likely be marked as a duplicate, but that duplicate will provide you your answer. Weird system, but it works. – David Arno Nov 17 '16 at 6:20
4

You can use constructor chaining to pass the dependency to a separate constructor in Derived, and then both pass that to the base constructor and set the field value:

class Base
{
    private BaseComponent component;

    protected Component
    {
        get { return component; }
    }

    Base(BaseComponent component)
}

class Derived : Base
{
    private DerivedComponent component;

    Derived() : this(new DerivedComponent())
    { }

    Derived(DerivedComponent component) : base(component)
    {
        this.component = component;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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