Generic Interfaces
A generic interface is a promise list with a fill-in-the-type blank, like a job that can be for a cook or a driver. Different classes can use it with different types.
In this page:
Syntax
interface IInterfaceName<T>
{
void Add(T item);
T Get();
}
class ClassName<T> : IInterfaceName<T>
{
// implement Add and Get
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Implementing a generic interface without a type argument, such as
class Box : IContainer, which does not compile becauseIContainer<T>needs itsT. - Treating
IContainer<int>andIContainer<string>as the same type, when each closed generic type is a separate type and they are not interchangeable. - Assuming an
IContainer<Dog>can be used where anIContainer<Animal>is expected, which is not allowed unless the interface is declared with variance (out/in).
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: