Abstract classes and interfaces
An abstract class is an incomplete base class that forces derived classes to fill in the missing parts, and an interface is a contract describing what a class can do. Knowing when to use which is one of the most asked C# interview questions.
16.1 The problem: Pay was forgotten
C#
new Upi(500).Pay();new Wallet(300).Pay(); class Payment(decimal amount){ public decimal Amount => amount; public virtual void Pay() => throw new NotImplementedException();}class Upi(decimal a) : Payment(a){ public override void Pay() => Console.WriteLine($"UPI: {Amount}");}class Wallet(decimal a) : Payment(a);Output
$ dotnet run Payment.csUPI: 500Unhandled exception.System.NotImplementedException: The method or operation is not implemented. at Payment.Pay() in Payment.cs:line 8- Pay in the base has a body (virtual + throw), so for the compiler Wallet is complete.
- The mistake shows up only at runtime, in front of the customer.
- Anyone can also create a plain Payment, which means nothing (a payment is always UPI, card or wallet).
16.2 abstract: the compiler catches it
- abstract class Payment: incomplete, cannot be instantiated (new Payment -> CS0144).
- abstract void Pay(); has no body: every derived class must override it.
- Wallet without Pay -> build fails with CS0534, before any customer sees it.
C#
abstract class Payment(decimal amount){ public decimal Amount => amount; public abstract void Pay();}class Upi(decimal a) : Payment(a){ public override void Pay() => Console.WriteLine($"UPI: {Amount}");}class Wallet(decimal a) : Payment(a);Output
$ dotnet run Payment.csPayment.cs(14,7): error CS0534: 'Wallet' does not implement inherited abstract member 'Payment.Pay()'The build failed. Fix the build errors and run again.- Step 1
1.Base Pay() is virtual + throw
- Step 2
2.Wallet forgets to override; compiler is silent
- Step 3
3.Crash at runtime in front of the customer
- Step 4
4.Make Pay() abstract (no body)
- Step 5
5.Wallet without Pay -> CS0534, build fails
- Step 6
6.Bug caught before deploy
16.3 Fix: an abstract class with concrete code
- An abstract class can mix abstract members, concrete methods (Receipt) and state (Amount).
- A variable of the abstract type is allowed: Payment p = new Wallet(300).
C#
Payment p = new Wallet(300);p.Pay(); p.Receipt(); abstract class Payment(decimal amount){ public decimal Amount => amount; public abstract void Pay(); public void Receipt() => Console.WriteLine($"Receipt: {Amount}");}class Wallet(decimal a) : Payment(a){ public override void Pay() => Console.WriteLine($"Wallet: {Amount}");}Output
$ dotnet run Payment.csWallet: 300Receipt: 30016.4 Interface: a contract
- Refund or SMS is a capability, not the identity of a payment: use an interface.
- IRefundable only says a Refund method must exist; names start with a capital I.
- One class can implement many interfaces (Upi : IRefundable, ISms), which base classes cannot do.
- Members are public by default; removing Send -> CS0535.
C#
var upi = new Upi(500);upi.Refund();upi.Send("9876543210"); interface IRefundable { void Refund(); }interface ISms { void Send(string phone); } class Upi(decimal amount) : IRefundable, ISms{ public void Refund() => Console.WriteLine($"Refund: {amount}"); public void Send(string phone) => Console.WriteLine($"SMS to {phone}");}Output
$ dotnet run Upi.csRefund: 500SMS to 987654321016.5 Interface rules: no state
C#
interface IRefundable{ decimal limit; IRefundable() { } void Refund();}Output
$ dotnet buildIRefundable.cs(3,13): error CS0525: Interfaces cannot contain instance fieldsIRefundable.cs(4,5): error CS0526: Interfaces cannot contain instance constructors- An interface says what must be done; storing data and creating objects is a class's job.
16.6 Default and static members
- Adding a new member to an existing interface would break every implementing class.
- A default member (Error with a body calling Log) adds behaviour without changing AppLogger.
- A static member is called on the interface name: ILogger.Create().
C#
ILogger log = ILogger.Create();log.Error("UPI timeout"); interface ILogger{ void Log(string msg); void Error(string msg) => Log($"ERROR: {msg}"); static ILogger Create() => new AppLogger();}class AppLogger : ILogger{ public void Log(string msg) => Console.WriteLine(msg);}Output
$ dotnet run Logger.csERROR: UPI timeout16.7 Checkpoint: default member via the class type
C#
var log = new AppLogger();log.Error("UPI timeout");Output
$ dotnet run Logger.csLogger.cs(2,5): error CS1061: 'AppLogger' does not contain a definition for 'Error'The build failed. Fix the build errors and run again.- A default member belongs to the interface, not the class; keep the variable type as ILogger to call Error.
16.8 Comparison: abstract class vs interface
| Point | Abstract class | Interface |
|---|---|---|
| Relation | is-a (Upi is a Payment) | can-do (Upi can refund) |
| State (fields) | Yes | No instance fields (CS0525) |
| Constructor | Yes (called via base) | No (CS0526) |
| Code | Abstract + concrete members | Default + static members (C# 8+) |
| How many per class | Only one base class | Many interfaces |
| Instantiate | No (CS0144) | No |
- Step 1
1.Need shared state or common code? -> abstract class
- Step 2
2.Describing a capability (refund, SMS)? -> interface
- Step 3
3.Class needs several capabilities? -> several interfaces
- Step 4
4.Both together: class Upi : Payment, IRefundable
Contract = interface, shared code = abstract class
16.9 Common mistakes
- One fat interface (IPayment with Pay + Refund): Cash must fake Refund with NotSupportedException, a false promise. Split into IPayment and IRefundable (interface segregation).
- Putting throw new NotImplementedException() in a virtual method instead of making it abstract.
- Thinking interfaces cannot contain code: since C# 8 they can have default and static members (still no fields or constructors).
- Thinking an abstract class has no constructor: it has one, and derived classes call it through base.
C#
interface IPayment { void Pay(); }interface IRefundable { void Refund(); } class Cash : IPayment{ public void Pay() => Console.WriteLine("Cash paid");}class Upi : IPayment, IRefundable{ public void Pay() => Console.WriteLine("UPI paid"); public void Refund() => Console.WriteLine("Refunded");}16.10 5 rules
- No meaningful default in the base? abstract method, not virtual + throw.
- Capability = interface, with the I prefix.
- Keep interfaces small and focused.
- Use default members only to evolve an interface.
- Shared state or code: abstract class.
16.11 Interview tips
- Abstract class: incomplete base, no object, can have fields, a constructor and concrete methods; only one base class.
- Interface: a contract with no state; a class can implement many.
- Modern C# interfaces have default and static members too.
- Rule of thumb: abstract class for is-a, interface for can-do.