O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required