I'm trying to understand Covariance and LSP. From this question I can see C# does not support return type covariance. However Liskov substitution principle imposes covariance on return type.
Does it mean it is impossible to apply this principle in C# ? Or did I missunderstand something ?
C# can still apply the Liskov substitution principle.
Consider:
public class Base1
{
}
public class Derived1 : Base1
{
}
public class Base2
{
public virtual Base1 Method()
{
return new Base1();
}
}
public class Derived2 : Base2
{
public override Base1 Method()
{
return new Derived1();
}
}
If C# supported covariant return types, then the override for Method()
in Base2
could be declared thusly:
public class Derived2 : Base2
{
public override Derived1 Method()
{
return new Derived1();
}
}
C# does not allow this, and you must declare the return type the same as it is in the base class, namely Base1
.
However, doing so does not make it violate the Liskov substitution principle.
Consider this:
Base2 test = new Base2();
Base1 item = test.Method();
Compared to:
Base2 test = new Derived2();
Base1 item = test.Method();
We are completely able to replace new Base2()
with new Derived2()
with no issues. This complies with the Liskov substitution principle.