Question

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?

Was it helpful?

Solution

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;
    }
}
Licensed under: CC-BY-SA with attribution
scroll top