Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 182 ยท Classes and Objects

Inheritance

Learn C# inheritance - base and derived classes, calling base constructors, protected members, sealed classes, is-a versus has-a and why composition often beats inheritance.

Inheritance lets one class build on another. You write a general class once, then create more specific classes that start with everything the general one has and add or change only what is different. A Dog is an Animal; a SavingsAccount is an Account; a Button is a Control. The general class is the base class (or parent), the specific one is the derived class (or child).

Used well, inheritance removes duplication and lets you treat many related objects through one common type. Used badly, it produces tangled hierarchies that nobody dares to change. This lesson teaches the mechanics (syntax, constructors, base, protected, sealed) and then the judgment: when "is-a" is true, when "has-a" is the better model, and why experienced C# developers say "prefer composition over inheritance".

The basics: a derived class

You declare a base class with a colon after the derived class name. The derived class gets all non-private members of its base:

C# A first derived class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three things happened. Dog reused Name and Eat without rewriting them. Dog added Bark. And a Dog object can be stored in an Animal variable, because every dog is an animal. That last point is the root of polymorphism. Through the Animal variable you can only use what Animal declares: pet.Bark() would not compile.

Rules to remember

  • A class can have one base class (single inheritance). It can implement many interfaces; see Abstract Classes and Interfaces.
  • If you declare no base class, the base is object. Every type in C# ultimately derives from object, which is why ToString() works on everything (The object Class).
  • Constructors are not inherited. Each class declares its own.
  • Structs cannot inherit from other structs or classes (they can implement interfaces). Records can inherit from other records (Records).
  • Private members still exist inside the derived object's memory, but derived code cannot name them.

Constructor chaining with base(...)

Before a Dog can exist, its Animal part must be initialized. That is why the derived constructor has to say how the base part is built, using : base(arguments). If the base class has a parameterless constructor, the call is optional and the compiler inserts : base() for you. If it does not, you must write it.

C# Order of constructor calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output shows the rule: base constructors run first, then the derived constructor body. With this(...) chaining, the target constructor runs completely before the body of the one that called it. Field initializers (int _x = 5;) run even earlier, before the base constructor call; Constructors and Object Initialization gives the exact order.

If you forget the base(...) call when the base has no parameterless constructor, the compiler rejects the class:

C# Missing base constructor call (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The message is error CS7036: There is no argument given that corresponds to the required parameter 'name' of 'Person.Person(string)'. Add : base(name) and it compiles. With primary constructors you pass arguments in the base list instead: class Worker(string name) : Person(name).

protected and what derived classes may touch

The derived class can use public and protected members of the base, but not private ones. protected is the deliberate "for subclasses only" door (see Access Modifiers).

C# Protected state and a template method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Report keeps its field private and offers a protected property, so subclasses can read the title but cannot corrupt it. Print is a template method: it fixes the steps and lets subclasses customize one of them by overriding Header. The keywords virtual and override are explained in Polymorphism.

Preventing inheritance with sealed

Inheritance is a promise to subclass authors, and promises are costly. If a class was not designed to be extended, say so with sealed:

C# Sealed classes (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS0509: 'SpecialToken': cannot derive from sealed type 'Token'. string and all structs are sealed. Make a class sealed by default unless you have a reason for subclasses: it gives the runtime a small optimization chance (calls to a sealed type's virtual methods can be devirtualized) but, more importantly, it lets you change internals later without breaking subclasses.

You can also seal a single overriding method (public sealed override string ToString()) to stop further overriding down the chain.

is-a versus has-a

How do you decide whether B should inherit from A? Ask: is every B truly an A, in every situation where an A is used? That is the Liskov substitution principle in plain words. A Dog is an Animal. A SavingsAccount is an Account. But:

  • A Stack is not a List; letting callers insert in the middle would break stack behavior.
  • A Car is not an Engine; a car has an engine.
  • A square is not a safe subclass of a rectangle if rectangles let you set width and height independently.

"Has-a" means composition: the object holds another object in a field and uses it. This is more flexible than inheritance because you choose the held object at runtime, you can swap it in tests, and the outer class does not expose the inner class's whole interface.

C# Composition instead of inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Car2 does not care which kind of power source it receives. With inheritance you would need GasCar, ElectricCar, HybridCar subclasses, and every new combination multiplies the hierarchy. With composition you add one small class.

A useful smell test: if you inherit only to reuse code, not because "B is an A" in the full sense, use composition. Inherit when you need substitutability: code written against A must work correctly with a B.

Shapes of inheritance: single, multilevel and hierarchical

C# lets a class have exactly one base class (single inheritance), but classes can be arranged in several shapes:

  • Single: Dog : Animal. One derived class, one base.
  • Multilevel: a chain, Animal <- Dog <- Puppy. Puppy inherits from both ancestors, and constructors run from the top down.
  • Hierarchical: one base with several siblings, Animal <- Dog and Animal <- Cat. Siblings share the base but know nothing about each other.
  • Multiple (not for classes): a class cannot have two base classes. To combine capabilities, implement several interfaces instead (see Abstract classes and interfaces).
C# Multilevel and hierarchical inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Creating a Puppy prints "Animal constructor", "Dog constructor", "Puppy constructor" in that order.

Benefits: shared code lives in one place, and a variable of the base type can hold any derived object. Costs: derived classes are tightly coupled to their base (a change in Animal can break every subclass), deep chains are hard to read, and the design is fixed at compile time.

Association, aggregation and composition

Classes relate in more ways than inheritance. The "has-a" relationships differ in how strongly the objects are tied together:

  • Association: one object uses another, for example a Teacher teaches a Student. Neither owns the other.
  • Aggregation: a whole holds parts, but the parts can exist without it. A Team has Players, yet the players survive if the team is disbanded.
  • Composition: the whole owns its parts and creates them; the parts have no meaning without it. A House has Rooms.
C# Aggregation versus composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

With a garbage collector, "the parts die with the whole" simply means nothing else holds a reference to them. Use association or aggregation when parts are shared or long-lived, and composition when a part has no life of its own. All three are preferred over deep inheritance when the relationship is "has-a" rather than "is-a".

Inheritance depth and design costs

  • Keep hierarchies shallow. Two or three levels are common; five is a warning sign. Each level adds behavior a reader has to track down.
  • The fragile base class problem. When a base class changes, every subclass changes behavior, sometimes in ways its author never tested. Seal classes and prefer small, focused base classes.
  • Don't override to disable. A subclass that throws NotSupportedException for an inherited method shows the hierarchy is wrong.
  • Don't call virtual methods in a constructor. The base constructor runs before the derived constructor has initialized its own fields, so an override may see half-built state.
C# Virtual call from a constructor (a classic trap)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first line prints Parent constructor sees: label not set yet: the Parent constructor called the override while Child's constructor body had not run, so _label was still null. (Had _label been given a value by a field initializer, that value would already be there, because field initializers run before the base constructor call. That makes the behavior depend on how the fields are assigned, which is exactly why this pattern is fragile.) Avoid virtual calls in constructors.

Checking and converting types in a hierarchy

Because a Dog is an Animal, you can upcast implicitly. Going down needs a check, because an Animal variable might hold a Cat:

C# Upcasting, downcasting and type tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Prefer is patterns or as to a raw cast. Needing many type checks usually means the behavior belongs in a virtual method instead, and Pattern Matching shows modern ways to branch on type when you do not control the hierarchy.

When to use and when to avoid

Use inheritance when: the types are a true is-a family; the base class is designed for extension (documented, with a small set of protected hooks); you want a common type for polymorphic code.

Avoid it when: you only want to reuse a few methods; the "child" needs to hide or disable parts of the parent; the hierarchy would need to grow along two independent axes (then use composition); the base type is not yours (many framework classes are not meant to be subclassed).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order do constructors run when you create a derived object?

    The base part must exist first, so the base constructor body runs before the derived constructor body.
  2. 2. What does the compiler report if a derived constructor omits base(...) and the base has only a constructor with a required parameter?

    Without a parameterless base constructor, the compiler cannot call one implicitly, so you must write : base(...).
  3. 3. What does sealed do on a class?

    A sealed class can be instantiated but not inherited (CS0509 if you try).
  4. 4. Which design is a better fit for 'a car has an engine you can swap'?

    A car is not an engine. Composition lets you choose or replace the part without changing Car.
  5. 5. Why is calling a virtual method from a base class constructor risky?

    The override can run while the derived constructor body has not yet executed, so it may observe incomplete state.

Summary

  • class Derived : Base inherits the accessible members of Base; a class has one base class, and object is the root of everything.
  • Constructors are not inherited; use : base(...) and : this(...). Base constructors run before the derived body.
  • protected exposes members to subclasses; sealed stops inheritance.
  • Inherit for true is-a substitutability; otherwise compose (has-a) and depend on interfaces.
  • Keep hierarchies shallow, avoid virtual calls in constructors, and prefer is/as over unchecked casts.

Next: Polymorphism: virtual, override and new