Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# return type covariance and Liskov substitution principle

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 ?

like image 542
Ythio Csi Avatar asked May 10 '17 12:05

Ythio Csi


1 Answers

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.

like image 82
Matthew Watson Avatar answered Nov 18 '22 22:11

Matthew Watson