Isaac.

programming

Inheritance in C#, TypeScript, and JavaScript

Understand inheritance patterns across languages.

By Emem IsaacJuly 18, 20232 min read
#inheritance#oop#class hierarchy#prototypes
Share:

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.

Share:

Written by Emem Isaac

Expert Software Engineer with 15+ years of experience building scalable enterprise applications. Specialized in ASP.NET Core, Azure, Docker, and modern web development. Passionate about sharing knowledge and helping developers grow.

Ready to Build Something Amazing?

Let's discuss your project and explore how my expertise can help you achieve your goals. Free consultation available.

💼 Trusted by 50+ companies worldwide | ⚡ Average response time: 24 hours