SkillPilotAI

Inheritance

Inheritance lets a derived class reuse the members of a base class and add its own, so common code lives in one place. In C# a class has exactly one base class, the base constructor always runs first, and sealed stops further inheritance.

14.1 Why is it used?

  • Two payment classes copy-paste Amount and Total().
  • GST changed from 12% to 18%; UpiPayment was updated, CardPayment was forgotten.
  • The same 1000 rupees gives 1180 for UPI and 1120 for card.
  • Tomorrow NetBankingPayment would make a third copy: we need common code written once.
C#
var upi = new UpiPayment { Amount = 1000 };var card = new CardPayment { Amount = 1000 };Console.WriteLine($"UPI:  {upi.Total()}");Console.WriteLine($"Card: {card.Total()}"); class UpiPayment{    public decimal Amount { get; set; }    public decimal Total() => Amount * 1.18m;}class CardPayment{    public decimal Amount { get; set; }    public decimal Total() => Amount * 1.12m;}
Output
$ dotnet run Payment.csUPI:  1180.00Card: 1120.00
How copy-paste becomes a bug
  1. 1.Same code copied into 2 classes

  2. 2.Rule changes: GST 12% -> 18%

  3. 3.One copy is updated, one is forgotten

  4. 4.Card keeps the old rate: 1120 instead of 1180

Needed: common code in one place = inheritance

14.2 Base class + derived class

  • Payment (base class) holds Amount and Total() once.
  • class UpiPayment : Payment { } means UpiPayment inherits from Payment (derived class).
  • Both derived classes are empty yet use Amount and Total(); a rate change is now a one-line edit.
C#
var upi = new UpiPayment { Amount = 1000 };var card = new CardPayment { Amount = 1000 };Console.WriteLine($"UPI:  {upi.Total()}");Console.WriteLine($"Card: {card.Total()}"); class Payment{    public decimal Amount { get; set; }    public decimal Total() => Amount * 1.18m;}class UpiPayment : Payment { }class CardPayment : Payment { }
Output
$ dotnet run Payment.csUPI:  1180.00Card: 1180.00

14.3 base: calling the base constructor

  • : base(amount) calls the Payment constructor first with the amount.
  • Then CardPayment sets its own Last4.
  • Base sets Amount, derived sets Last4.
C#
var card = new CardPayment(1000, "4242");Console.WriteLine($"{card.Last4} {card.Amount}"); class Payment{    public decimal Amount { get; }    public Payment(decimal amount) => Amount = amount;}class CardPayment : Payment{    public string Last4 { get; }    public CardPayment(decimal amount,        string last4) : base(amount)        => Last4 = last4;}
Output
$ dotnet run Card.cs4242 1000

14.4 Forgetting the base call

  • Without : base(...), the compiler looks for a parameterless base constructor.
  • Payment only has Payment(decimal amount), so the build fails with CS7036.
  • Rule: if the base has no parameterless constructor, the derived class must call base(...).
C#
var card = new CardPayment("4242"); class Payment{    public decimal Amount { get; }    public Payment(decimal amount)        => Amount = amount;}class CardPayment : Payment{    public string Last4 { get; }    public CardPayment(string last4)        => Last4 = last4;}
Output
$ dotnet run Card.csCard.cs(12,12): error CS7036: There is no  argument given that corresponds to the  required parameter 'amount' of  'Payment.Payment(decimal)'The build failed. Fix the build errors and run again.

14.5 How it works: constructor order

Constructor order
  1. 1.new CardPayment(1000, "4242"): object creation starts

  2. 2.base(amount): Payment constructor runs first, sets Amount

  3. 3.CardPayment body runs, sets Last4

  4. 4.Object ready: both parts set

Base first, then derived: foundation before the upper floor

C#
new CreditCard(); class Payment{    public Payment() => Console.WriteLine("Payment");}class Card : Payment{    public Card() => Console.WriteLine("Card");}class CreditCard : Card{    public CreditCard() => Console.WriteLine("CreditCard");}
Output
$ dotnet run Order.csPaymentCardCreditCard
  • Each constructor first calls its base constructor, so the chain goes to the top before any body runs.
  • No explicit base here, so the compiler calls the parameterless base constructor.

14.6 sealed: no inheritance

  • sealed class UpiPayment: nobody can inherit from it (e.g. sensitive payment logic).
  • class FakeUpi : UpiPayment -> CS0509.
  • Many .NET classes like string are sealed; the runtime can also optimize some calls on sealed types.
C#
var upi = new UpiPayment(); class Payment{    public decimal Amount { get; set; }}sealed class UpiPayment : Payment{    public string UpiId { get; set; } = "";}class FakeUpi : UpiPayment { }
Output
$ dotnet run Upi.csUpi.cs(11,17): error CS0509: 'FakeUpi':  cannot derive from sealed type 'UpiPayment'The build failed. Fix the build errors and run again.

14.7 Comparison: inheritance vs composition

PointInheritanceComposition
Relationis-a (CardPayment is a Payment)has-a (OrderService has a Logger)
Syntaxclass B : AField / constructor parameter of type A
CouplingTight: all public members of A become part of BLoose: only what you call
LimitOnly one base classAny number of parts
Use whenReal is-a + shared codeYou only need reuse
C#
// Wrong: OrderService "is a" Logger? No!class OrderService : Logger{    public void Place()        => Log("Order placed");} // Right: OrderService "has a" Loggerclass OrderService(Logger logger){    public void Place()        => logger.Log("Order placed");}

14.8 Common mistakes

  • Inheriting only to reuse code (OrderService : Logger): every public Logger member leaks into OrderService. Use composition.
  • Thinking a class can have two base classes: only one base class is allowed (CS1721). For multiple contracts use interfaces.
  • Deep hierarchies: after about three levels the code gets hard to follow.
  • Forgetting : base(...) when the base has no parameterless constructor (CS7036).
  • Fun fact: every class automatically inherits from object, which is why ToString(), Equals() and GetType() exist on every object.

14.9 5 rules of inheritance

  1. Only for a real is-a relation.
  2. Common code in the base class.
  3. Call the base constructor with base(...).
  4. Not meant for extension? Mark it sealed.
  5. No deep hierarchies; for plain reuse, compose.

14.10 Interview tips

  • Inheritance: a derived class reuses base members and adds new ones; C# allows only one base class.
  • On creation the base constructor runs first, then the derived one; base(...) passes values up.
  • sealed blocks inheritance (string is sealed).
  • is-a -> inheritance, has-a -> composition; prefer composition when you only need reuse.