Generic interfaces let you create flexible blueprints that work with any data type. This helps you write code that can handle many kinds of data without repeating yourself.
Generic interfaces in C Sharp (C#)
interface IMyInterface<T> { void DoSomething(T item); T GetItem(); }
The <T> after the interface name means it is generic and uses a placeholder type T.
Classes that implement this interface must specify the actual type for T and implement the methods using that type.
T.interface IRepository<T> { void Add(T item); T FindById(int id); }
IRepository for strings. It stores strings in a list.class StringRepository : IRepository<string> { private List<string> items = new(); public void Add(string item) => items.Add(item); public string FindById(int id) => items[id]; }
T.interface IComparer<T> { int Compare(T a, T b); }
This program shows a generic interface IContainer<T> and a class Container<T> that implements it. It stores items of any type. We create containers for int and string and print their items.
using System; using System.Collections.Generic; interface IContainer<T> { void AddItem(T item); T GetItem(int index); } class Container<T> : IContainer<T> { private List<T> items = new(); public void AddItem(T item) => items.Add(item); public T GetItem(int index) => items[index]; } class Program { static void Main() { IContainer<int> intContainer = new Container<int>(); intContainer.AddItem(10); intContainer.AddItem(20); Console.WriteLine(intContainer.GetItem(0)); Console.WriteLine(intContainer.GetItem(1)); IContainer<string> stringContainer = new Container<string>(); stringContainer.AddItem("hello"); stringContainer.AddItem("world"); Console.WriteLine(stringContainer.GetItem(0)); Console.WriteLine(stringContainer.GetItem(1)); } }
Generic interfaces help avoid repeating code for different types.
When implementing a generic interface, you must specify the type or keep it generic.
You can use multiple generic parameters like interface IPair.
Generic interfaces use placeholders for types to make code reusable.
They define methods or properties that work with any specified type.
Classes implement these interfaces by specifying the actual type.