← Back to C# Course | Chapter 11: Generics | Lesson 4 of 6

Generic Interfaces

In this page:

  1. Generic Interfaces

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

markup
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());
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.