Isaac.

Inheritance in C#, TypeScript, and JavaScript

Understand inheritance patterns across languages.

By EMEPublished: February 20, 2025
inheritanceoopclass hierarchyprototypes

A Simple Analogy

Inheritance is like biological inheritance. Children inherit traits from parents and can override them.


Why Inheritance?

  • Reuse: Share common code
  • Hierarchy: Model relationships
  • Polymorphism: Different implementations
  • Maintenance: Change in one place
  • Clarity: Express intent through hierarchy

C# Inheritance

public abstract class Animal
{
    public string Name { get; set; }
    
    public virtual void MakeSound()
    {
        Console.WriteLine("Some sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Woof");
    }
}

var dog = new Dog { Name = "Rex" };
dog.MakeSound();  // Outputs: Woof

TypeScript Inheritance

class Animal {
  name: string;
  
  constructor(name: string) {
    this.name = name;
  }
  
  makeSound(): void {
    console.log("Some sound");
  }
}

class Dog extends Animal {
  makeSound(): void {
    console.log("Woof");
  }
}

const dog = new Dog("Rex");
dog.makeSound();  // Outputs: Woof

JavaScript Prototypes

function Animal(name) {
  this.name = name;
}

Animal.prototype.makeSound = function() {
  console.log("Some sound");
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.makeSound = function() {
  console.log("Woof");
};

const dog = new Dog("Rex");
dog.makeSound();  // Outputs: Woof

Best Practices

  1. Favor composition: Often better than inheritance
  2. Shallow hierarchies: Keep 2-3 levels deep
  3. Interface segregation: Use interfaces
  4. Single responsibility: One reason to change
  5. Liskov substitution: Derived types are substitutable

Related Concepts

  • Polymorphism
  • Composition
  • Interfaces
  • Abstract classes

Summary

Inheritance enables code reuse. C# and TypeScript provide explicit syntax, while JavaScript uses prototypes.