Interface-Based Constraints

An example is in order. Suppose that we want to create a collection that can keep elements sorted. To make the collection maximally applicable, we want to declare it as a generic type. However, just creating an OrderedList<T> is too permissive because not every type is suitable for sorting purposes. So, we want to constrain the flexibility on the type parameter T by saying we only allow “types T that are orderable.” What makes a type orderable? That starts to smell like a contract, something that can be enforced by the implementation of a certain interface. IComparable<T> comes to mind:

public interface IComparable<in T> {    int CompareTo(T other);}

If we can compare any two objects of ...

Get C# 5.0 Unleashed 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.