C#
Interfaces & Abstract Classes
6 question(s)
What is the difference between an interface and an abstract class?
Beginner
An abstract class can hold state and shared implementation and supports single inheritance; an interface is a contract a type can implement many of. Use interfaces for capabilities, abstract classes for a shared base.
public interface IPayable { decimal Pay(); }
public abstract class Employee : IPayable { public string Name=""; public abstract decimal Pay(); }
Real-world example
IPayable expresses the capability; Employee shares Name across subtypes.
Why program to an interface rather than a concrete type?
Beginner
Depending on an abstraction decouples callers from implementations, enabling substitution, testing with mocks, and dependency injection.
public OrderService(IOrderRepository repo) { }
Real-world example
Swapping a SQL repository for an in-memory fake in unit tests without changing OrderService.
What are default interface methods and when are they useful?
Intermediate
Since C# 8 an interface can provide a default method body, letting you add members to an interface without breaking existing implementers.
interface ILogger { void Log(string m); void LogError(string m) => Log("ERR: "+m); }
Real-world example
Extending a widely-implemented library interface without forcing every implementer to change.
Can a class implement two interfaces with the same method? How is it resolved?
Intermediate
Yes. If signatures clash you can implement the members explicitly, qualified by interface name, so each interface gets its own behaviour accessible via that interface type.
class C : IA, IB { void IA.Do(){} void IB.Do(){} }
Real-world example
Explicit implementation hides a rarely-used interface method from the public surface.
When would you choose an abstract class over an interface for extensibility?
Advanced
When you need shared state or non-trivial common implementation, versioning with protected members, or to control the construction of derived types — things interfaces cannot express as cleanly.
public abstract class HttpHandlerBase { protected readonly HttpClient Http; ... }
Real-world example
A framework base class that provides plumbing and calls abstract hooks (template method pattern).
What is the Interface Segregation Principle and how does it apply in C#?
Advanced
Clients should not depend on methods they do not use; prefer several small, focused interfaces over one large one, so implementers and consumers stay decoupled.
// instead of IRepository with 20 methods:
interface IReadRepository<T> { Task<T?> GetAsync(int id); }
Real-world example
Splitting a fat service interface so a read-only consumer needn't depend on write methods.