Inheritance
By the end of this lesson you'll be able to build a family of related classes that share code through inheritance, replace behaviour with virtual / override , and write one piece of code that works for every type via polymorphism — the OOP pillars that keep large programs flexible.
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
Inheritance is like biology. "Dog", "Cat" and "Bird" are all specialised kinds of "Animal": they inherit the general traits (a name, the ability to eat) and then add or change their own (a dog barks, a bird flies). You write the shared parts once in the base class instead of copying them into every animal. Polymorphism is like a universal remote's "play" button — you press the same button, but it does the right thing depending on whether a TV, a speaker, or a games console is listening. In code, you call Speak() on an Animal and each object responds in its own way.
📋 Inheritance Keywords Reference
Keyword
Where it goes
What it does
:
Class header
class Dog : Animal — Dog inherits Animal
: base(...)
Constructor
Calls the parent's constructor
virtual
Base method
Allows derived classes to override it
override
Derived method
Replaces the base implementation
base.X()
Calls the parent's version of a method
abstract
Class / method
Cannot be instantiated; must be implemented
sealed
Prevents any further inheritance/override
is
Expression
if (a is Dog d) — check & cast
as
a as Cat — cast, or null on failure
1. Base & Derived Classes
A base class (the parent) holds traits shared by a whole family of things. A derived class (the child) is written with class Child : Parent and automatically gets every public field, property and method of the parent — you don't rewrite them. The phrase to remember is "is a" : a Car is a Vehicle , so Car : Vehicle is correct. When the parent has a constructor with parameters, the child must pass them up with : base(...) . The base constructor runs first, then the child's. Read this worked example, run it, then you'll write your own.
Your turn. The Dog class is already written for you at the bottom. Fill in the two blanks marked ___ in Main so Dog is recognised as an Animal and you call the method it inherited.
2. Overriding with virtual & override
Inheriting a method gives you the parent's behaviour, but often a child needs to do something different. Mark the base method virtual ("you may replace me") and the child's version override ("I'm replacing it"). The magic part: even when the object is stored in a variable typed as the base class, C# runs the actual object's override at runtime. That is polymorphism — "many shapes" — one method name, the right behaviour for each type.
Now you try. FrenchGreeter needs to override Greet() . Fill in the keyword that replaces the base method and the French greeting it should return.
🔎 Deep Dive: extend, don't copy, with base.Method()
Sometimes you don't want to replace the parent's method — you want to add to it. From inside an override , call base.MethodName() to run the parent's version, then do your extra work. This keeps the shared logic in one place instead of copying it into every child.
3. Polymorphism, is & as
Polymorphism really pays off when you treat a mixed bag of objects uniformly. Store different derived objects in one base-typed array ( Animal[] ), loop over them once, and each call lands on the correct override — no if / switch on the type. When you do need the specific type, is checks and casts in a single step ( if (a is Dog dog) ), and as attempts a cast that yields null instead of crashing if it fails.
4. Abstract Classes (vs Interfaces)
An abstract class is a base class you can never new directly — it only exists to be inherited. It can hold shared fields and finished methods, plus abstract methods that have no body and that every child must implement. That makes it a contract with some implementation baked in. An interface is a pure contract — method signatures only, no fields, and a class can implement many interfaces but inherit only one class. Rule of thumb: use an abstract class when relatives share state and code ( Employee → Contractor ); use an interface for a capability unrelated classes can share ( IComparable , IDisposable ).
🔎 Deep Dive: sealed — closing a class for inheritance
The opposite of abstract is sealed : it marks a class as final so nothing can inherit from it. Use it when a class is complete and you don't want subclasses changing its behaviour — it also lets the runtime optimise calls. You can also seal a single override to stop deeper classes overriding it again.
Pro Tips
- 💡 Override needs virtual: a method is only overridable if the base marks it virtual (or abstract ). No virtual , no override .
- 💡 Reuse with base : call base.Method() inside an override to extend the parent instead of copy-pasting its body.
- 💡 Favour composition over deep trees: keep hierarchies to 2–3 levels; if "is a" feels forced, a "has a" field is usually better.
- 💡 Abstract class vs interface: abstract = shared state + code; interface = a capability many unrelated classes can opt into.
- 💡 Pattern matching beats casting: if (a is Dog d) is safer and shorter than checking then casting on two lines.
Common Errors (and the fix)
- "CS0506 / CS0507: cannot override … not marked virtual, abstract, or override" — you wrote override on a method whose base version isn't virtual . Add virtual to the base method.
- Warning "CS0114: … hides inherited member; use the new keyword or override " — you redeclared a method without override , so it hides the base one and polymorphism breaks. Add override (almost always what you want).
- "CS1729: '…' does not contain a constructor that takes N arguments" — your : base(...) call doesn't match any parent constructor. Pass the exact arguments the base constructor expects.
- "CS7036 / no argument given that corresponds to required parameter" — the parent has only a parameterised constructor, so the child must call : base(...) . Add it.
- "CS0144: cannot create an instance of the abstract type" — you tried to new an abstract class. Instantiate a concrete derived class instead.
- "CS0509: cannot derive from sealed type" — you tried to inherit from a sealed class. Remove sealed , or use composition instead of inheritance.
📋 Quick Reference
Task
Code
Notes
Inherit a class
class Dog : Animal
Dog "is a" Animal
Call parent constructor
: base(name)
Runs before child body
Allow overriding
public virtual void X()
On the base method
Replace behaviour
public override void X()
On the derived method
Reuse parent method
Inside the override
Must-implement method
public abstract void X();
In an abstract class
Check & cast
if (a is Dog d)
d is typed Dog inside
Safe cast
a as Cat
null if it isn't a Cat
Frequently Asked Questions
Q: What's the difference between override and new on a method?
override truly replaces the base method, so polymorphism works — a base-typed reference calls your version. new only hides the base method; which one runs depends on the variable's declared type, not the real object. You almost always want override .
Q: When should I use an abstract class instead of an interface?
Use an abstract class when the children are genuine relatives that share fields and some finished code ( Employee → Manager ). Use an interface for a capability unrelated classes can share (e.g. anything "comparable" or "disposable"). A class can implement many interfaces but inherit from only one class.
Q: Why must I write : base(...) sometimes but not always?
If the parent only has a constructor that takes arguments, the child must supply them with : base(...) . If the parent has a parameterless constructor, C# calls it for you automatically and you can omit : base() .
Q: Is is better than casting with (Dog)animal ?
Yes, for safety. A direct cast throws InvalidCastException if the object isn't that type. if (animal is Dog dog) checks first and only enters the block when the cast is valid, and as returns null instead of throwing — both avoid crashes.
Mini-Challenge: Shape Areas
No blanks this time — just a brief and an outline. Build a small shape hierarchy, override Area() in each shape, then loop over a Shape[] and print every area. This is the exact pattern real graphics, billing and reporting code uses.
🎉 Lesson Complete
- ✅ class Child : Parent inherits every public member of the base class
- ✅ : base(...) chains constructors; the base runs first
- ✅ virtual on the base + override on the child = replaceable behaviour
- ✅ base.Method() reuses the parent's logic instead of copying it
- ✅ Polymorphism: one base-typed loop calls the right override for each object
- ✅ abstract classes set contracts; interface for capabilities; sealed to lock down; is / as to check and cast safely
- ✅ Next lesson: Collections — List, Dictionary, Stack, Queue, and more
Practice quiz
How do you make Dog inherit from Animal?
- class Dog extends Animal
- class Dog -> Animal
- class Dog : Animal
- class Dog inherits Animal
Answer: class Dog : Animal. C# uses a colon: class Dog : Animal means Dog is a derived class of Animal.
What does : base(name) in a derived constructor do?
- Passes arguments up to the base class constructor
- Creates a new field
- Calls a static method
- Overrides a method
Answer: Passes arguments up to the base class constructor. : base(...) passes data to the parent constructor, which runs before the child's body.
A method can only be overridden if the base marks it with which keyword?
- override
- sealed
- static
- virtual (or abstract)
Answer: virtual (or abstract). The base method must be virtual (or abstract) before a derived class may override it.
Which keyword does the derived class use to replace a virtual method?
- virtual
- override
- new
- base
Answer: override. override on the derived method replaces the base implementation and enables polymorphism.
What does calling base.Log(message) inside an override do?
- Runs the parent's version of the method
- Calls the child's version
- Throws an error
- Skips the method
Answer: Runs the parent's version of the method. base.Method() runs the parent's implementation so you can extend it instead of copying it.
When Animal a1 = new Dog("Rex"); calls a1.Speak(), whose version runs?
- Animal's, because the variable is typed Animal
- Neither — it errors
- Dog's override, chosen at runtime
- Both
Answer: Dog's override, chosen at runtime. Polymorphism: C# runs the actual object's override (Dog's) even through a base-typed reference.
What is true about an abstract class?
- You can create it with new directly
- It cannot be instantiated and exists only to be inherited
- It cannot have any methods
- It is the same as sealed
Answer: It cannot be instantiated and exists only to be inherited. An abstract class can't be newed up directly; it serves as a base for derived classes.
What must every derived class do with an abstract method?
- Ignore it
- Call base on it
- Seal it
- Implement (override) it
Answer: Implement (override) it. An abstract method has no body, so each concrete derived class MUST implement it.
What does the sealed keyword on a class do?
- Makes it abstract
- Prevents any class from inheriting from it
- Hides all its methods
- Makes it static
Answer: Prevents any class from inheriting from it. sealed marks a class as final — nothing can derive from it (CS0509 if you try).
What does if (animal is Dog dog) do?
- Always throws if not a Dog
- Converts animal to a Dog forcibly
- Checks the type and, if it matches, casts to dog in one step
- Compares animal to the text "Dog"
Answer: Checks the type and, if it matches, casts to dog in one step. The is pattern tests the runtime type and safely assigns the cast value to dog only when it matches.
Continue this course
- Previous: Object-Oriented Programming
- Next: Collections