๐Ÿ  VisualStudioTutor.com  ยท  C# Tutorial Home  ยท  C# Lesson 7 of 40
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 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}");
}

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);
}

Part 4: Interface vs Abstract Class

InterfaceAbstract Class
Multiple inheritanceโœ… Many interfacesโŒ One only
ConstructorsโŒ Noneโœ… Yes
FieldsโŒ Noneโœ… Yes
Default implโœ… Optionalโœ… Yes
Use whenCapability contractShared 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