1

In the following code, compiler complains about B not implementing TestProperty of abstract class A. ITest2 is derived from ITest1 so it implements everything ITest1 has. Why is this not possible?

public interface ITest1 { }
public interface ITest2 : ITest1 { }

public abstract class A
{
    public abstract ITest1 TestProperty { get; set; }
}

public class B:A
{
    public override ITest2 TestProperty { get; set; }
}
PersyJack
  • 1,736
  • 1
  • 21
  • 32
  • If you are going to down-vote so quickly, can you at least care to explain? – PersyJack Feb 17 '15 at 19:41
  • What you are asking for is called covariance. See http://stackoverflow.com/questions/5709034 and http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Inheritance_in_object_oriented_languages – Moby Disk Feb 17 '15 at 20:59

2 Answers2

8

This wouldn't be safe since you could do:

interface ITest3 : ITest1 { }
public class Test3 : ITest3 { }

A b = new B();
b.TestProperty = new Test3();

however Test3 does not implement ITest2 as required by B.

Lee
  • 142,018
  • 20
  • 234
  • 287
2

Make A class generic

Public abstract class A<TTest>
    Where TTest : ITest1
 {
    Public abstract TTest TestProperty {get; set;}
 }

 Public class B : A<ITest2>
 {
 ....
 }