📋 Interfaces = Contracts
Interfaces define contracts. Interfaces enable polymorphism, abstraction, loose coupling.
📝 Interface Basics
// Interface definition
public interface IUserService
{
Task GetUserAsync(int id);
Task CreateUserAsync(User user);
Task UpdateUserAsync(User user);
Task DeleteUserAsync(int id);
}
// Implementation
public class UserService : IUserService
{
public async Task GetUserAsync(int id)
{
// Implementation
}
public async Task CreateUserAsync(User user)
{
// Implementation
}
public async Task UpdateUserAsync(User user)
{
// Implementation
}
public async Task DeleteUserAsync(int id)
{
// Implementation
}
}
// Interface with properties
public interface IUser
{
int Id { get; }
string Name { get; set; }
string Email { get; set; }
}
// Interface inheritance
public interface IRepository
{
Task GetByIdAsync(int id);
Task> GetAllAsync();
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
}
public interface IUserRepository : IRepository
{
Task GetByEmailAsync(string email);
}
🎯 Using Interfaces
// Dependency Injection
public class UserController
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
}
// Multiple implementations
public class EmailNotification : INotification
{
public async Task SendAsync(string message)
{
// Send email
}
}
public class SmsNotification : INotification
{
public async Task SendAsync(string message)
{
// Send SMS
}
}
// Interface with default methods (C# 8+)
public interface ILogger
{
void Log(string message);
void LogError(string message)
{
Log($"ERROR: {message}");
}
}
// Generic interface
public interface IValidator
{
bool Validate(T entity);
}
// Interface segregation
public interface IReadable
{
Task GetByIdAsync(int id);
Task> GetAllAsync();
}
public interface IWritable
{
Task AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(int id);
}
// Interface Benefits
- Polymorphism
- Abstraction
- Loose coupling
- Testability
- Dependency injection
💡 Interface Tips
- Use for abstraction
- Enable polymorphism
- Support dependency injection
- Improve testability
- Follow Interface Segregation Principle
“Interfaces define contracts. Polymorphism, abstraction, loose coupling. Essential for OOP.”
