Generic Interfaces
Abstract over types.
What Is a Generic Interface?
A generic interface declares type parameters in angle brackets after its name. Implementers choose the concrete types, and the interface contract adapts accordingly.
The .NET library uses them everywhere, for example IEnumerable<T> and IComparable<T>.
interface IRepository<T>
{
void Add(T item);
T Get(int id);
}Implementing a Generic Interface
A class can implement a generic interface by supplying a concrete type argument. The method signatures then use that real type.
This produces a type-safe, reusable contract without casts.
using System.Collections.Generic;
class IntStore : IRepository<int>
{
private readonly List<int> data = new();
public void Add(int item) => data.Add(item);
public int Get(int id) => data[id];
}
interface IRepository<T>
{
void Add(T item);
T Get(int id);
}All lessons in this course
- Generic Methods
- Generic Classes
- where Constraints
- Generic Interfaces