Generic Interfaces
In this page:
Generic Interfaces
Interfaces can also be generic, like the built-in IComparable<T> or IEnumerable<T>, letting a contract be parameterized by type just like a class. A class implementing IContainer<T> commits to working with one specific type T chosen at implementation time. This keeps interface contracts precise and type-safe rather than relying on object.
Note: Prefer generic interfaces like IEnumerable<T> over their non-generic ancestors like IEnumerable to avoid manual casting.
Example: Generic Interfaces
using System;
interface IContainer<T>
{
void Add(T item);
T GetFirst();
}
class SingleItemContainer<T> : IContainer<T>
{
private T item;
public void Add(T item)
{
this.item = item;
}
public T GetFirst()
{
return item;
}
}
class Program
{
static void Main(string[] args)
{
IContainer<string> container = new SingleItemContainer<string>();
container.Add("first item");
Console.WriteLine(container.GetFirst());
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: