Tools
Log in
English

Learn to codeC#

C# inheritance

Based on C# 12collection expression [ ] · C# 12+

C# inheritance with base, virtual, override, sealed, and hiding with new.

In one line

Write : ParentClass after the class name to take over the parent’s properties and methods, then replace only the methods the parent opened with virtual, using override.

Why you need it

Separate classes for staff, managers and interns would each carry a name, a base salary and a pay calculation. Change the pay rule and you edit three places; miss one and people get paid by different rules.

Keep the shared part once in Employee and use override only for what really differs, like the team allowance for managers or the meal allowance for interns.

Everyday picture

Think of a company handbook. Everyone follows the same book, and the manager supplement lists only the changes, such as "add an allowance per team member". The supplement may only change chapters the handbook marks as changeable (virtual).

Example code

Program.cs · 68 lines
Employee[] staff =[    new Employee("Hana", 3_000_000m),    new Manager("Dojin", 4_000_000m, 3),    new Intern("Yuri"),];foreach (Employee e in staff){    Console.WriteLine($"{e.Name}: {e.MonthlyPay():N0} ({e.Badge()})");}Manager boss = (Manager)staff[1];Console.WriteLine($"{boss.Name} as Manager: {boss.Badge()}"); class Employee{    public string Name { get; }    protected decimal BaseSalary { get; }     public Employee(string name, decimal baseSalary)    {        Name = name;        BaseSalary = baseSalary;    }     public virtual decimal MonthlyPay()    {        return BaseSalary;    }     public string Badge()    {        return "staff";    }} class Manager : Employee{    private readonly int teamSize;     public Manager(string name, decimal baseSalary, int teamSize) : base(name, baseSalary)    {        this.teamSize = teamSize;    }     public override decimal MonthlyPay()    {        decimal pay = base.MonthlyPay() + teamSize * 200_000m;        return pay;    }     public new string Badge()    {        return "manager";    }} sealed class Intern : Employee{    public Intern(string name) : base(name, 1_800_000m)    {    }     public override decimal MonthlyPay()    {        decimal pay = base.MonthlyPay() + 100_000m;        return pay;    }}

When to use it

  • "A manager is an employee" is always true
  • Several classes share properties and behavior and differ in only a few spots
  • You want to handle many children through one parent type (Employee[]). That is the next topic, polymorphism.

A C# class has one parent class. To promise several things, add several interfaces (abstraction topic).

Hiding with new is an emergency exit for name clashes with a parent you cannot change. Use virtual and override day to day.

Common mistakes

Leaving out virtual and override

Without virtual on the parent method, a same-named child method hides it instead of overriding it. The compiler only warns (CS0108), and calls through a parent-typed variable get the parent result. Pair virtual in the parent with override in the child.

Wrong

Employee e = new Manager("Dojin", 4_000_000m);Console.WriteLine(e.MonthlyPay()); class Employee(string name, decimal baseSalary){    public string Name => name;     public decimal MonthlyPay() => baseSalary;} class Manager(string name, decimal baseSalary) : Employee(name, baseSalary){    public decimal MonthlyPay() => 9_999_999m;}

When you run it4000000

Fixed

Employee e = new Manager("Dojin", 4_000_000m);Console.WriteLine(e.MonthlyPay()); class Employee(string name, decimal baseSalary){    public string Name => name;     public virtual decimal MonthlyPay() => baseSalary;} class Manager(string name, decimal baseSalary) : Employee(name, baseSalary){    public override decimal MonthlyPay() => 9_999_999m;}

When you run it9999999

Putting override on a method that is not virtual

override only works on methods the parent opened with virtual (or abstract). If you own the parent, mark it virtual; otherwise override a method that allows it.

Wrong

class Lead : Employee{    public Lead(string name) : base(name, 5_000_000m)    {    }     public override string Badge() => "lead";}

What the C# compiler sayserror CS0506: 'Lead.Badge()': cannot override inherited member 'Employee.Badge()' because it is not marked virtual, abstract, or override

Fixed

class Lead : Employee{    public Lead(string name) : base(name, 5_000_000m)    {    }     public override decimal MonthlyPay() => base.MonthlyPay() + 300_000m;}

Inheriting from a sealed class

sealed means inheritance stops here. If you need a variation, inherit from the parent (Employee) instead, or talk to whoever sealed it.

Wrong

class SummerIntern : Intern{    public SummerIntern(string name) : base(name)    {    }}

What the C# compiler sayserror CS0509: 'SummerIntern': cannot derive from sealed type 'Intern'

Fixed

class SummerIntern : Employee{    public SummerIntern(string name) : base(name, 1_500_000m)    {    }}

Check yourself

Question 1

A Manager is stored in an Employee variable. What is printed?

Employee e = new Manager("Ara", 2_000_000m, 1);Console.WriteLine($"{e.MonthlyPay():N0} {e.Badge()}");

Show the answer

Answer: 2. 2,200,000 staff MonthlyPay is an override, so it follows the object (Manager): 2,000,000 + 200,000. Badge is only hidden with new, so it follows the variable type (Employee): staff.

Question 2

In which order do the constructors run for new Manager(...)?

Show the answer

Answer: 3. The parent constructor runs first : base(...) runs the parent constructor first to fill the inherited parts (name, base salary), then the child body fills its own part (team size). Steps 2 and 3 of the step-through show this order.

Questions people ask

What is the difference between override and new?

override is chosen by the object’s real type, new by the variable’s type. Through a parent-typed variable, an override runs the child version while a new method runs the parent version.

Why can’t C# methods be overridden by default?

Only methods the parent opens with virtual can change, so the author of the parent decides what may vary. Java takes the opposite default.

When should I use sealed?

On classes whose rules would break if someone inherited from them. You can also write sealed override on a single method to stop further overriding of just that method.