In a derived class, how to have a property of a derived type from the type of the property in the base class?

This is a huge design problem that I often encounter and I think it is because I don't understand OOP right.

Here is the class of the base Property :

public class BasePropety {}

Here is the type of my DerivedProperty:

public class DerivedProperty : BaseProperty
{
    public AClass A { get; set; }
}

Here is my base class :

public class BaseClass
{
    public BaseProperty Property { get; set; }
}

Here my derived class :

public class DerivedClass : BaseClass
{
    public DerivedProperty Property { get; set; }

    public void MethodExample()
    {
        AClass aValue = this.Property.A;
    }
}

I could of course typecast my property but it is annoying:

public class DerivedClass : BaseClass
{
    public void MethodExample()
    {
        var typedProperty = (DerivedProperty) this.Property;
        AClass aValue = typedProperty.A;
    }
}

I know I can use the new keyword but I read here and there that it is a bad practice, so how I am suppose to achieve this ? Should I create a new property ?

Thanks in advance for your answers.

Jon Skeet
people
quotationmark

Sounds like you need generics instead:

public class BaseClass<T> where T : BaseProperty
{
    public T Property { get; set; }
}

public class DerivedClass : BaseClass<DerivedProperty>
{
    public void MethodExample()
    {
        AClass aValue = Property.A;
    }
}

Note that this means there's only one property - whereas in your current code, you actually have two independent properties, which happen to have the same name. I suspect you don't want that.

people

See more on this question at Stackoverflow