LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

SOLID - Liskov Substitution Principle

LSP says that an object of a child class should be usable wherever its parent class is expected, without breaking the program. It helps us build reliable and predictable applications.

Liskov Substitution Principle in C# – Write Safe and Replaceable Subtypes

Quick Answer: The Liskov Substitution Principle says a child type must work wherever its parent type is expected. It must keep the promises made by the parent. A child type should not surprise the code that uses it.

In this article, we will use hospital appointments to understand this rule. We will first see a broken design, then fix it with C#.

1. What Is the Liskov Substitution Principle?

Imagine a hospital booking system. It supports in-person and online appointments.

Both appointment types share some basic actions. A patient can confirm either appointment. The system can also display its instructions.

However, an online appointment has a meeting link. An in-person appointment has a hospital location instead.

Now imagine that the system treats every appointment as an online appointment. The in-person appointment cannot provide a meeting link.

Should the in-person appointment fail when the system asks for that link?

No. The parent type should not promise something that every child cannot provide.

Liskov Substitution Principle (LSP) = child types must safely replace their parent type.

A child type can add its own features. But it must preserve the parent's expected behaviour.

Remember: Inheritance is not only about sharing code. It is also about keeping behaviour compatible.

2. The Problem: A Parent Class Makes the Wrong Promise

Suppose a hospital system manages 50,000 appointments. It supports online and in-person visits.

We create one parent class called HospitalAppointment. It provides a method to get a meeting link.

But this method does not make sense for every appointment type.

Example 1: A parent class with an incorrect contract

This design assumes every hospital appointment is online.

using System;

public class HospitalAppointment
{
    public string PatientName { get; }

    public HospitalAppointment(string patientName)
    {
        PatientName = patientName;
    }

    public virtual string GetMeetingLink()
    {
        return "https://hospital.example/meeting";
    }
}

public class OnlineAppointment : HospitalAppointment
{
    public OnlineAppointment(string patientName)
        : base(patientName) { }
}

public class InPersonAppointment : HospitalAppointment
{
    public InPersonAppointment(string patientName)
        : base(patientName) { }

    public override string GetMeetingLink()
    {
        throw new NotSupportedException(
            "In-person appointments do not have meeting links.");
    }
}

public class Program
{
    public static void Main()
    {
        HospitalAppointment[] appointments =
        {
            new OnlineAppointment("Priya"),
            new InPersonAppointment("Ravi")
        };

        foreach (var appointment in appointments)
        {
            Console.WriteLine(appointment.PatientName);
            Console.WriteLine(appointment.GetMeetingLink());
        }
    }
}

Expected output

Priya
https://hospital.example/meeting
Ravi
Unhandled exception. System.NotSupportedException:
In-person appointments do not have meeting links.

What happened? The code works for the online appointment. It fails for the in-person appointment. The child class cannot safely replace the parent class.

What Goes Wrong?

  1. Unexpected exceptions: A valid appointment can fail during normal processing.
  2. Extra type checks: Callers must check the actual child type.
  3. Fragile code: Adding appointment types can break existing callers.
  4. Broken expectations: The parent promises behaviour that some children cannot provide.
  5. Harder testing: Each caller needs special tests for every child type.

Now think about 50,000 appointments. These special cases become difficult to maintain.

3. The Solution: Design a Contract Every Appointment Can Follow

First, keep only shared behaviour in the parent class.

Every appointment can confirm its booking. Every appointment can also provide instructions.

Only online appointments should provide a meeting link.

Interface = a contract that lists the actions a type must provide.

We will use a separate interface for online meeting details. This keeps the parent contract valid for every appointment.

Step 1: Create the Shared Appointment Base Class

Example 2: A base class with valid shared behaviour

Both appointment types can confirm and display their instructions.

using System;

public abstract class HospitalAppointment
{
    public string PatientName { get; }
    public string AppointmentTime { get; }

    protected HospitalAppointment(
        string patientName,
        string appointmentTime)
    {
        PatientName = patientName;
        AppointmentTime = appointmentTime;
    }

    public void Confirm()
    {
        Console.WriteLine(
            $"Appointment confirmed for {PatientName} at {AppointmentTime}.");
    }

    public abstract string GetInstructions();
}

Step 2: Create a Contract for Online Appointments

Example 3: A separate online appointment capability

Only appointment types that support online meetings implement this interface.

public interface IOnlineAppointment
{
    string GetMeetingLink();
}

Step 3: Create the Appointment Types

Example 4: Online and in-person appointment classes

Each class now follows the contract that applies to it.

public class OnlineAppointment
    : HospitalAppointment, IOnlineAppointment
{
    public OnlineAppointment(
        string patientName,
        string appointmentTime)
        : base(patientName, appointmentTime) { }

    public override string GetInstructions()
    {
        return "Join the hospital video consultation.";
    }

    public string GetMeetingLink()
    {
        return "https://hospital.example/consultation";
    }
}

public class InPersonAppointment
    : HospitalAppointment
{
    private readonly string _hospitalLocation;

    public InPersonAppointment(
        string patientName,
        string appointmentTime,
        string hospitalLocation)
        : base(patientName, appointmentTime)
    {
        _hospitalLocation = hospitalLocation;
    }

    public override string GetInstructions()
    {
        return $"Visit {_hospitalLocation} for your appointment.";
    }
}

Step 4: Use Both Types Through the Parent Class

Example 5: A complete runnable program

The booking service works with both appointment types.

using System;

public abstract class HospitalAppointment
{
    public string PatientName { get; }
    public string AppointmentTime { get; }

    protected HospitalAppointment(
        string patientName,
        string appointmentTime)
    {
        PatientName = patientName;
        AppointmentTime = appointmentTime;
    }

    public void Confirm()
    {
        Console.WriteLine(
            $"Confirmed: {PatientName} at {AppointmentTime}");
    }

    public abstract string GetInstructions();
}

public interface IOnlineAppointment
{
    string GetMeetingLink();
}

public class OnlineAppointment
    : HospitalAppointment, IOnlineAppointment
{
    public OnlineAppointment(
        string patientName,
        string appointmentTime)
        : base(patientName, appointmentTime) { }

    public override string GetInstructions()
    {
        return "Join the online consultation.";
    }

    public string GetMeetingLink()
    {
        return "https://hospital.example/consultation";
    }
}

public class InPersonAppointment
    : HospitalAppointment
{
    private readonly string _location;

    public InPersonAppointment(
        string patientName,
        string appointmentTime,
        string location)
        : base(patientName, appointmentTime)
    {
        _location = location;
    }

    public override string GetInstructions()
    {
        return $"Visit {_location}.";
    }
}

public class Program
{
    public static void Main()
    {
        HospitalAppointment[] appointments =
        {
            new OnlineAppointment("Priya", "10:00 AM"),
            new InPersonAppointment(
                "Ravi", "11:30 AM", "Bengaluru Hospital")
        };

        foreach (var appointment in appointments)
        {
            appointment.Confirm();
            Console.WriteLine(appointment.GetInstructions());
            Console.WriteLine();
        }

        var onlineAppointment =
            (IOnlineAppointment)appointments[0];

        Console.WriteLine(
            "Meeting link: " + onlineAppointment.GetMeetingLink());
    }
}

Expected output

Confirmed: Priya at 10:00 AM
Join the online consultation.

Confirmed: Ravi at 11:30 AM
Visit Bengaluru Hospital.

Meeting link: https://hospital.example/consultation

Why is this better? The booking service uses the parent type for shared actions. Online meeting details are available only through the online appointment contract. No appointment needs to throw an exception for a normal operation.

4. How the Correct Design Works

The next diagram shows how the booking service uses the shared contract. Both appointment types follow that contract. Only the online type adds meeting support.

LSP Architecture – Safe Appointment Substitution

Draw.io-inspired class and dependency flow

Appointment Booking Service Uses the common appointment type Caller
uses the shared contract
HospitalAppointment Confirm() · GetInstructions() Parent contract
can be replaced by either subtype
Online visit
OnlineAppointment Shared actions + meeting link LSP compatible
Hospital visit
InPersonAppointment Shared actions + location LSP compatible
IOnlineAppointment GetMeetingLink() Online-only capability
implemented by online appointments only
OnlineAppointment Provides the meeting link Specialized contract
Compatible behaviour Shared or specialized contract

The booking service can replace the parent with either appointment subtype without breaking shared operations.

What Does the Animation Show?

  • The booking service starts the request.
  • The shared parent contract defines the expected actions.
  • The request can use either appointment subtype.
  • The online-specific capability remains separate.

The animation highlights each stage automatically. The text remains stationary and sharp.

5. Check the Contract: Broken Design vs Correct Design

LSP is about behaviour, not only matching method names. A child class must keep the promises made by its parent.

Contract Compatibility Check

Two designs, one important difference

Broken inheritance

Every appointment must return a meeting link.

In-person appointment throws an exception.

FAIL – Contract broken
Corrected design

Every appointment confirms and gives instructions.

Only online appointments provide meeting links.

PASS – Contract preserved

Automatic contract check: broken promise → valid shared contract

The comparison highlights why optional capabilities should not be forced into a shared parent contract.

6. Step-by-Step Code Breakdown

6.1 The Parent Class Defines Shared Behaviour

  • HospitalAppointment represents every hospital appointment.
  • Confirm() works for both appointment types.
  • GetInstructions() gives instructions for each type.
  • The parent does not promise a meeting link.

6.2 The Child Classes Keep the Parent Contract

  • OnlineAppointment confirms and gives online instructions.
  • InPersonAppointment confirms and gives hospital instructions.
  • Both classes support the expected parent operations.
  • Neither class rejects a valid shared operation.

6.3 The Specialized Interface Adds One Capability

  • IOnlineAppointment describes online meeting support.
  • Only online appointments implement that interface.
  • The booking service does not need meeting details for every appointment.
  • This avoids forcing unrelated behaviour onto other appointment types.

6.4 What Does Substitution Mean?

Substitution means using a child object where the parent type is expected.

For example, the booking service accepts a HospitalAppointment.

It can receive an online appointment or an in-person appointment. Its shared operations continue to work.

7. Liskov Substitution Principle Rules

These rules help us check whether a child type follows its parent contract.

7.1 Do Not Strengthen Preconditions

A precondition is something that must be true before a method runs.

A child method should not demand more than the parent method demands.

For example, if the parent accepts a valid patient name, the child should not reject that same valid name without a clear contract reason.

7.2 Do Not Weaken Postconditions

A postcondition is what the caller can expect after a method finishes.

A child must keep the parent's promised result.

If the parent promises a confirmed appointment, the child should not silently return an unconfirmed booking.

7.3 Preserve Invariants

An invariant is a rule that must always remain true.

For example, a confirmed appointment must keep its patient and appointment time.

A child class must not break that rule.

7.4 Do Not Replace Normal Behaviour with Exceptions

A child should not throw an exception for an operation the parent promises to support.

That is why the in-person appointment should not reject a shared appointment operation.

LSP behaviour rules in simple words
Rule Meaning Hospital example
Preconditions Do not demand more from callers. Accept the same valid appointment details.
Postconditions Keep the promised result. Confirm the appointment as expected.
Invariants Keep important rules true. Preserve the patient's booking details.
Exceptions Do not reject valid parent operations. Do not require a meeting link for every visit.

8. Common LSP Mistakes and Best Practices

Mistake 1: Throwing NotSupportedException in an Override

Wrong approach: A child overrides a parent method but cannot support it.

Why it fails: Callers expect the parent method to work.

Better approach: Move optional behaviour into a separate interface or a suitable abstraction.

Mistake 2: Checking the Child Type Everywhere

Wrong approach: Callers use many checks such as is OnlineAppointment.

Why it fails: Callers become tightly connected to concrete classes.

Better approach: Depend on the shared contract for shared operations. Use a specialized contract only when that capability is needed.

Mistake 3: Inheriting Only to Reuse Code

Wrong approach: A class inherits from another class only to reuse a few methods.

Why it fails: The child may inherit promises it cannot keep.

Better approach: Prefer composition when the types do not share a true behavioural relationship.

Mistake 4: Returning Fake Values

Wrong approach: An in-person appointment returns an empty meeting link.

Why it fails: The caller may treat an empty value as a valid link.

Better approach: Do not expose that capability through the common parent contract.

Mistake 5: Testing Only the Parent Class

Wrong approach: Tests cover only the base class behaviour.

Why it fails: A child class may break the contract later.

Better approach: Run the same shared contract tests against every subtype.

9. How to Test LSP in C#

Contract tests check whether different child types follow the same parent promises.

For this example, both appointment types must confirm and provide instructions.

Example 6: A simple shared contract test

This example uses plain C# assertions without an external test package.

using System;
using System.Collections.Generic;

public static class AppointmentContractTests
{
    public static void CheckSharedContract(
        IEnumerable<HospitalAppointment> appointments)
    {
        foreach (var appointment in appointments)
        {
            if (string.IsNullOrWhiteSpace(appointment.PatientName))
            {
                throw new Exception("Patient name is required.");
            }

            if (string.IsNullOrWhiteSpace(appointment.GetInstructions()))
            {
                throw new Exception("Instructions are required.");
            }

            appointment.Confirm();
        }
    }
}

Testing note: This is a simple contract-check example. In a real project, place the checks in your test project and run them against every appointment subtype.

10. LSP and Other SOLID Principles

LSP is the third principle in SOLID. Each principle helps us build code that is easier to change.

Five SOLID principles
Principle Main idea
Single Responsibility Principle A class should have one clear responsibility.
Open/Closed Principle Allow new behaviour without changing stable code.
Liskov Substitution Principle Child types must safely replace parent types.
Interface Segregation Principle Keep interfaces focused on related actions.
Dependency Inversion Principle Depend on abstractions, not concrete details.

LSP also supports the Open/Closed Principle. New appointment types should not break existing booking code.

It works well with Interface Segregation too. Small interfaces avoid forcing unrelated actions onto classes.

11. How This Comes Up in Interviews

Question 1: What Is the Liskov Substitution Principle?

What the interviewer wants: They want to know whether you understand inheritance behaviour.

Strong answer:

Liskov Substitution Principle says a child class must safely replace its parent class. The child must preserve the behaviour expected by the parent. In a hospital booking system, both online and in-person appointments should support shared booking operations. We should not make an in-person appointment throw an exception for a meeting link. That capability belongs only to online appointments.

Question 2: How Can You Identify an LSP Violation?

Strong answer:

I look for child classes that reject valid parent operations. I also check for unexpected exceptions and extra type checks. If callers need special rules for one child, I review the parent contract. I then move optional behaviour into a more suitable abstraction.

Question 3: Is Every Inheritance Relationship an LSP Relationship?

Strong answer:

No. Sharing fields or methods does not prove that inheritance is correct. The child must also preserve the parent's expected behaviour. If it cannot do that, I consider composition or a smaller interface.

Question 4: How Does LSP Relate to Interface Segregation?

Strong answer:

Both principles help keep contracts clear. LSP says child types must honour their contracts. Interface Segregation says a type should not depend on actions it does not need. In our example, meeting links belong to an online appointment contract, not every appointment.

What Interviewers Expect at Different Levels

  • Junior developer: Explain the rule and identify a basic violation.
  • Senior developer: Show a better class design and explain the trade-offs.
  • Technical architect: Explain contract design, test strategy, compatibility and long-term change.

12. Hands-On Practice

Beginner Exercise: Add a Pharmacy Consultation

Add a new appointment type for a pharmacy consultation.

  • It must confirm the appointment.
  • It must provide consultation instructions.
  • It must not require an online meeting link.

Hint: Inherit from HospitalAppointment only if the shared contract still makes sense. Otherwise, create a more suitable shared appointment abstraction.

Intermediate Exercise: Add a Video Follow-Up

Add a video follow-up appointment type.

  • It must support the shared appointment contract.
  • It must implement IOnlineAppointment.
  • It must return a valid sample meeting link.

Expected result: The booking service should process it as a normal appointment. Online-specific code should access its meeting link.

Advanced Exercise: Write Contract Tests

Create a test method for every appointment subtype.

  • Check that patient names are available.
  • Check that instructions are not empty.
  • Check that confirmation works.
  • Check that online appointments provide meeting links.
  • Check that shared operations do not depend on the concrete type.

Expected result: Adding a new subtype should not break existing contract tests.

13. Frequently Asked Questions

Can a child class add new methods?

Yes. A child can add new behaviour. It must still preserve the parent's promises.

Does LSP apply only to abstract classes?

No. It also applies to normal inheritance and interface implementations. The main concern is compatible behaviour.

Is throwing an exception always an LSP violation?

No. Exceptions can be valid when the contract allows them. The problem is rejecting an operation that the parent promises to support.

Can interfaces help us follow LSP?

Yes. Small interfaces can describe separate capabilities. This avoids forcing unrelated behaviour onto every subtype.

Should we always prefer composition over inheritance?

No. Use inheritance when the types share a valid behavioural relationship. Use composition when one type only needs another type's functionality.

14. Next Steps and Community

What You Learned

  • LSP keeps inheritance behaviour compatible.
  • Child classes must preserve parent expectations.
  • Do not force optional operations into a shared parent.
  • Use focused interfaces for separate capabilities.
  • Test every subtype against the shared contract.

Continue the SOLID Series

Next, explore SOLID – Interface Segregation Principle. Learn how focused interfaces help classes depend only on the actions they need.

Share Your Knowledge

Try the examples and create your own appointment types. Share your implementation and discuss other design choices with the Upgradix community.

Final thought: Good inheritance keeps promises. A child type should never surprise its caller.

Upgradix by Shrash Studio
Learn Technology. Build Your Future.
Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.