C# Interface IComparable


This entry is part 8 of 8 in the series C# Interfaces

When dealing with objects, you often want to make comparisons between them. This is especially important in collections, because it is how sorting is achieved. You can also sort collections with IComparer.

The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress has some example code that we will look at. We will start with an array of integers. The Array class has a sort method so this is easy to do, as you can see in the code below.

using System;
namespace IComparableArray
{
    class Program
    {
        static void Main(string[] args)
        {
            var myInt = new[] { 20, 4, 16, 9, 2 }; // Create an array of ints.
            Array.Sort(myInt); // Sort elements by magnitude.
            foreach (var i in myInt) // Print them out.
                Console.Write($"{ i } ");
            Console.WriteLine();
        }
    }
}
Series Navigation<< C# Interfaces Illustrated