Lesson 7 of 40
OOP
Intermediate
โฑ 35 min
Interfaces & Abstract Classes
Design flexible systems with interfaces, default interface methods, explicit implementation, and understand when to choose interface vs abstract class.
Part 1: Defining & Implementing Interfaces
public interface IRepository<T>
{
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task SaveAsync(T entity);
Task DeleteAsync(int id);
}
Any class that implements {
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task SaveAsync(T entity);
Task DeleteAsync(int id);
}
IRepository<T> must provide all four methods, enabling DI and testability.Part 2: Default Interface Methods
public interface ILogger
{
void Log(string message);
// Default implementation โ no need to override
void LogError(string msg) => Log($"[ERROR] {msg}");
void LogInfo(string msg) => Log($"[INFO] {msg}");
}
{
void Log(string message);
// Default implementation โ no need to override
void LogError(string msg) => Log($"[ERROR] {msg}");
void LogInfo(string msg) => Log($"[INFO] {msg}");
}
Part 3: Explicit Interface Implementation
public class DualLogger : IConsoleLogger, IFileLogger
{
// Resolves name clash
void IConsoleLogger.Write(string s) => Console.WriteLine(s);
void IFileLogger.Write(string s) => File.AppendAllText("log.txt", s);
}
{
// Resolves name clash
void IConsoleLogger.Write(string s) => Console.WriteLine(s);
void IFileLogger.Write(string s) => File.AppendAllText("log.txt", s);
}
Part 4: Interface vs Abstract Class
| Interface | Abstract Class | |
|---|---|---|
| Multiple inheritance | โ Many interfaces | โ One only |
| Constructors | โ None | โ Yes |
| Fields | โ None | โ Yes |
| Default impl | โ Optional | โ Yes |
| Use when | Capability contract | Shared base behavior |
C# in Visual Studio 2026
๐ This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition