C# Multiple Interfaces - Implementation Guide
Implementing Multiple Interfaces
One of the key advantages of interfaces in C# is that a class can implement multiple interfaces, overcoming the limitation of single inheritance. This allows a class to combine behaviors from different sources while keeping the design modular.
When implementing multiple interfaces, a class must provide implementations for all members of all interfaces. If multiple interfaces define members with the same signature, explicit interface implementation can be used to avoid ambiguity.
Basic Multiple Interface Implementation
This example demonstrates how a class can implement multiple interfaces and use explicit implementation to resolve method name conflicts:
using System;
public interface IFlyable
{
void Fly();
int MaxAltitude { get; }
}
public interface ISwimmable
{
void Swim();
int MaxDepth { get; }
}
public interface IEnginePowered
{
void StartEngine();
void StopEngine();
}
public interface IManualPowered
{
void StartEngine();
void Pedal();
}
public class AmphibiousVehicle : IFlyable, ISwimmable, IEnginePowered
{
public int MaxAltitude => 10000;
public int MaxDepth => 100;
public void Fly() => Console.WriteLine($"Flying at altitude: {MaxAltitude} feet");
public void Swim() => Console.WriteLine($"Swimming at depth: {MaxDepth} feet");
public void StartEngine() => Console.WriteLine("Engine started");
public void StopEngine() => Console.WriteLine("Engine stopped");
public void DriveOnLand() => Console.WriteLine("Driving on land");
}
public class HybridVehicle : IEnginePowered, IManualPowered
{
public void StartEngine() => Console.WriteLine("Electric engine started");
public void StopEngine() => Console.WriteLine("Electric engine stopped");
void IManualPowered.StartEngine() => Console.WriteLine("Manual power engaged");
public void Pedal() => Console.WriteLine("Pedaling...");
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Amphibious Vehicle ===");
AmphibiousVehicle vehicle = new AmphibiousVehicle();
vehicle.Fly();
vehicle.Swim();
vehicle.StartEngine();
vehicle.DriveOnLand();
vehicle.StopEngine();
Console.WriteLine("\n=== Hybrid Vehicle ===");
HybridVehicle hybrid = new HybridVehicle();
IEnginePowered engine = hybrid;
IManualPowered manual = hybrid;
engine.StartEngine();
manual.StartEngine();
hybrid.Pedal();
engine.StopEngine();
}
}
=== Amphibious Vehicle === Flying at altitude: 10000 feet Swimming at depth: 100 feet Engine started Driving on land Engine stopped === Hybrid Vehicle === Electric engine started Manual power engaged Pedaling... Electric engine stopped
Advanced Multiple Interface Patterns
When working with multiple interfaces, common patterns include interface segregation, adapter design, and dependency injection. These patterns promote flexibility and maintainability.
The interface segregation principle recommends designing small, focused interfaces so that classes only implement what they actually need, avoiding unnecessary methods.
using System;
using System.Collections.Generic;
public interface IReadableRepository<T>
{
T GetById(int id);
IEnumerable<T> GetAll();
}
public interface IWritableRepository<T>
{
void Add(T item);
void Update(T item);
void Delete(int id);
}
public interface ISearchableRepository<T>
{
IEnumerable<T> Search(string criteria);
}
public interface IRepository<T> : IReadableRepository<T>, IWritableRepository<T>, ISearchableRepository<T>
{
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductRepository : IRepository<Product>
{
private List<Product> products = new List<Product>();
private int nextId = 1;
public Product GetById(int id) => products.Find(p => p.Id == id);
public IEnumerable<Product> GetAll() => products;
public void Add(Product product)
{
product.Id = nextId++;
products.Add(product);
}
public void Update(Product product)
{
var existing = GetById(product.Id);
if (existing != null)
{
existing.Name = product.Name;
existing.Price = product.Price;
}
}
public void Delete(int id) => products.RemoveAll(p => p.Id == id);
public IEnumerable<Product> Search(string criteria) => products.FindAll(p => p.Name.Contains(criteria, StringComparison.OrdinalIgnoreCase));
}
public class ProductCatalogService
{
private readonly IReadableRepository<Product> repository;
public ProductCatalogService(IReadableRepository<Product> repository) => this.repository = repository;
public void DisplayProducts()
{
Console.WriteLine("Product Catalog:");
foreach (var product in repository.GetAll())
{
Console.WriteLine($"{product.Id}: {product.Name} - ${product.Price}");
}
}
}
public class ProductManagementService
{
private readonly IWritableRepository<Product> repository;
public ProductManagementService(IWritableRepository<Product> repository) => this.repository = repository;
public void AddProduct(string name, decimal price)
{
repository.Add(new Product { Name = name, Price = price });
Console.WriteLine("Product added successfully");
}
}
class Program
{
static void Main(string[] args)
{
IRepository<Product> repository = new ProductRepository();
repository.Add(new Product { Name = "Laptop", Price = 999.99m });
repository.Add(new Product { Name = "Mouse", Price = 25.50m });
repository.Add(new Product { Name = "Keyboard", Price = 75.00m });
Console.WriteLine("=== Catalog Service ===");
var catalogService = new ProductCatalogService(repository);
catalogService.DisplayProducts();
Console.WriteLine("\n=== Management Service ===");
var managementService = new ProductManagementService(repository);
managementService.AddProduct("Monitor", 299.99m);
Console.WriteLine("\n=== Updated Catalog ===");
catalogService.DisplayProducts();
Console.WriteLine("\n=== Search Results ===");
foreach (var product in repository.Search("o"))
{
Console.WriteLine($"Found: {product.Name}");
}
}
}
=== Catalog Service === Product Catalog: 1: Laptop - $999.99 2: Mouse - $25.50 3: Keyboard - $75.00 === Management Service === Product added successfully === Updated Catalog === Product Catalog: 1: Laptop - $999.99 2: Mouse - $25.50 3: Keyboard - $75.00 4: Monitor - $299.99 === Search Results === Found: Mouse Found: Monitor Found: Keyboard