PersyJack
PersyJack

Reputation: 1964

Why can't a derived class override base class' interface type abstract property with a type that extends that interface?

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; }
}

Upvotes: 1

Views: 96

Answers (2)

Evgenii Koroliuk
Evgenii Koroliuk

Reputation: 132

Make A class generic

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

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

Upvotes: 2

Lee
Lee

Reputation: 144106

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.

Upvotes: 8

Related Questions