4.1. Implementing a System Interface: IComparable

Let's start by implementing our own class instance of a predefined interface within the System namespace. The motivational context is the following: We need to sort an ArrayList of strings in ascending order by the length of the string. OK. That sounds simple enough. So how are we going to do that? If we look at the public methods of ArrayList, we see that it provides an overloaded pair of Sort() member functions:

System.Collections.ArrayList

Sort: Overloaded.
Sorts the elements in the ArrayList, or a portion of it.

Let's look at the documentation for the two different methods and see which one, if either, fits the bill. Here's the one with an empty parameter list:

 public virtual void Sort() ...

Get C# Primer: A Practical Approach 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.