Interfaces and Generics

Like classes or structures, interfaces too can be defined in terms of generic type parameters.[*] Generic interfaces provide all the benefits of interface-based programming without compromising type safety, performance, or productivity. All of what you have seen so far with normal interfaces you can also do with generic interfaces. The main difference is that when deriving from a generic interface, you must provide a specific type parameter to use instead of the generic type parameter. For example, given this definition of the generic IList<T> interface:

    public interface IList<T>
    {
       void AddHead(T item);
       void RemoveHead(T item);
       void RemoveAll();
    }

you can implement the interface implicitly and substitute an integer for the generic type parameter:

    public class NumberList : IList<int>
    {
       public void AddHead(int item)
       {...}
       public void RemoveHead(int item)
       {...}
       public void RemoveAll()
       {...}
       //Rest of the implementation
    }

When the client uses IList<T>, it must choose an implementation of the interface with a specific type parameter:

    IList<int> list = new NumberList();
    list.AddHead(3);

Generic interfaces allow you to define an abstract service definition (the generic interface) once, yet use it on multiple components with multiple type parameters. For example, an integer-based list can implement the interface:

    public class NumberList : IList<int>
    {...}

And so can a string-based list:

    public class NameList : IList<string>
    {...}

Once a generic interface is bounded (i.e., ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.