Lesson 8: Interfaces in C#
Interfaces define contracts — lists of methods and properties that a class must implement. Unlike abstract classes, interfaces provide no implementation and allow multiple inheritance. This lesson covers defining, implementing, and using interfaces effectively.
What Is an Interface?
An interface is a contract specifying what methods/properties a class must implement. By convention, interface names start with 'I':
public interface IPayable
{
void Pay(decimal amount);
decimal GetBalance();
}
public class Employee : IPayable
{
private decimal _balance;
public void Pay(decimal amount)
{
_balance -= amount;
}
public decimal GetBalance()
{
return _balance;
}
}
// Usage
IPayable person = new Employee();
person.Pay(100);
Multiple Interface Implementation
A class can implement multiple interfaces (but can only inherit from one class):
public interface ILoggable
{
void Log(string message);
}
public interface IReportable
{
string GenerateReport();
}
public class Service : ILoggable, IReportable
{
public void Log(string message)
{
Console.WriteLine($"[LOG] {message}");
}
public string GenerateReport()
{
return "Service Report";
}
}
Properties in Interfaces
Interfaces can declare properties that implementing classes must provide:
public interface IUser
{
string Name { get; set; }
int Age { get; }
bool IsActive { get; set; }
}
public class Admin : IUser
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsActive { get; set; }
}
Interface vs Abstract Class
Use interfaces for contracts (what a class does). Use abstract classes for shared behavior (what a class is):
// Abstract class: shared behavior
public abstract class Animal
{
public void Sleep() { Console.WriteLine("Sleeping"); }
public abstract void Eat();
}
// Interface: contract
public interface IMovable
{
void Move();
}
// Usage: class can implement interface AND inherit from abstract
public class Dog : Animal, IMovable
{
public override void Eat() { Console.WriteLine("Eating dog food"); }
public void Move() { Console.WriteLine("Running"); }
}
Default Interface Implementations (C# 8.0+)
Modern C# allows interfaces to provide default implementations:
public interface ILogger
{
void Log(string message);
// Default implementation
void LogError(string message)
{
Log($"[ERROR] {message}");
}
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
// LogError is inherited with default implementation
}
🧠 Quick Check — Lesson 8
Can a class implement multiple interfaces?
Lesson Summary
Interfaces define contracts specifying what methods/properties a class must implement.
A class can implement multiple interfaces but can only inherit from one class.
Use interfaces for "what a class does" and abstract classes for "what a class is."
C# 8.0+ allows interfaces to provide default implementations.
Interfaces promote loose coupling and are essential for dependency injection and testing.