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

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:

  1. Generic Interfaces
Syntax
csharp
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

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());
    }
}
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
  1. Implementing a generic interface without a type argument, such as class Box : IContainer, which does not compile because IContainer<T> needs its T.
  2. Treating IContainer<int> and IContainer<string> as the same type, when each closed generic type is a separate type and they are not interchangeable.
  3. Assuming an IContainer<Dog> can be used where an IContainer<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:

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.