Building C# Comparable Objects: IComparable versus IComparer
(Page 1 of 4 )
Working with object-oriented languages (like C#) is all about manipulating objects. We create objects, change objects properties, save objects states, and sort objects. The part we are concentrating on in this article is sorting objects.
Objects that are part of the language (such as strings) can be sorted without any additional work on our end. But when it comes to classes that we create (Book, Employee, Car…), we need to give hints to the runtime on how objects of these classes can be sorted (what does it mean that book1 comes before book2? Are they sorted by title? By ISBN?...). The hints that we give to the runtime are the interfaces. We implement interfaces such as IComparable and IComparer so the runtime can tell how to compare and sort objects.
Interface definition: An interface is a named collection of abstract methods. Abstract means that the methods are not implemented. It is left up to the user of the interface to implement these methods the way he/she sees fit. When you create an interface you are creating a contract, which means that any code implementing the interface needs to implement all the methods in the interface (you simply cannot pick and choose which methods to implement).
To create an interface you use the keyword interface followed by the name of the interface. Interfaces do not specify a base class, and all interface members are implicitly public. Here is an interface declaration:
interface IDraw
{
void Draw();
}
By convention, interface names are prefixed by the letter ‘I’. Based on this declaration, any class that needs to implement the interface IDraw must provide implementation for the method Draw(). Let’s create a class named Circle that implements the IDraw Interface:
class Circle : IDraw
{
public override void Draw()
{
Console .WriteLine( "Drawing a circle." );
}
}
Next: Sorting Objects >>
More C# Articles
More By Ayad Boudiab