Search code examples
c#oopsolid-principles

When Liskov Substitution refers to subtypes, is it talking about derived classes in the context of C#?


I'm unfamiliar with the word 'subtype' after looking at the wikipedia article.

I took Liskov substitution to mean if you have a method that takes an Animal, you should be able to pass in a Cat or an Animal where Cat : Animal without any unintended side effects.

Is this what Liskov substitution refers to?


Solution

  • Exactly. Anything that takes an Animal should be able to take a Dog, a Cat, and subclasses (breeds, if you like). The methods will be compatible.

    Note also that preconditions cannot be strengthened in a subtype, nor can postconditions be weakened. Otherwise you could slot in a particular subtype and that would break because the surrounding code had imposed certain preconditions that the subclass couldn't tolerate. This can be difficult to implement in practise - see the circle/ellipse problem for more info.