Inherit from an abstract class with properties of a different type (.NET 3.5, C #)

I have 3 of the following classes:

public class BaseProperty1{
    public string Property1 {get; set;}
}

public class ChildProperty1 : BaseProperty1 {

}

public abstract class Base{
    public abstract BaseProperty1 bp1 {get; set;}
}

I am trying to get the following class from Base:

public class Child : Base{
    public ChildProperty1 bp1 {get; set;}
}

But I get an error that the install and get methods are not implemented. Is this just the syntax I'm using, or is my way of thinking wrong?

Thank!

+3
source share
2 answers

You will not be able to use Auto Properties, since you need to exactly match the type of base class. You have to go the old fashioned way:

public abstract class Child : Base
{
    private ChildProperty1 _bp1;

    public BaseProperty1 bp1
    {
        get { return _bp1; }

        // Setter will be tricky. This implementation will default to null
        // if the cast is bad.
        set { _pb1 = value as ChildProperty1; }
    }
}

You can also use generics to solve the problem:

public abstract class Parent<TProp> where TProp : BaseProperty1
{
    public abstract T bp1 { get; set; }
}

public abstract class Child : Parent<ChildProperty1>
{
    public ChildProperty1 bp1 { get; set; }
}
+5
source

abstract, . (bp1 ) :

public abstract class Base{
    public BaseProperty1 bp1 {get; set;} //without abstract identifier
}

public class Child : Base
{
       public new ChildProperty1 bp1 { get; set; } // with new modifier
}
0

All Articles