Interfaces define contracts without implementation—like Java interfaces but C# allows explicit interface implementation and default interface methods (C# 8+). Use interfaces when multiple unrelated types share a capability.
Interface example
interface IShape {
double Area();
}
class Circle : IShape {
public double Radius { get; }
public Circle(double r) => Radius = r;
public double Area() => Math.PI * Radius * Radius;
}
Program to interfaces (IShape) so callers stay decoupled from concrete types—essential before DI containers in ASP.NET.
Important interview questions and answers
- Q: Abstract class vs interface?
A: Abstract classes can hold state and shared implementation; interfaces are pure contracts (with optional defaults)—prefer interfaces for capability mixing. - Q: Why virtual on base methods?
A: Withoutvirtual, overrides are hidden, not polymorphic—calls through base references won't dispatch to derived code.
Self-check
- What makes polymorphism work through a base reference?
- Can a struct implement an interface?
Tip: A class can implement many interfaces—prefer small, focused interfaces over one giant contract.
Interview prep
- Interface vs abstract class?
Interfaces define contracts without state; abstract classes can share implementation and fields—a class inherits one base but many interfaces.
- Explicit interface implementation?
Implement an interface member with the interface prefix—callable only through the interface type, not the class directly.