...

/

Implementing Interfaces: Comparing Objects When Sorting

Implementing Interfaces: Comparing Objects When Sorting

Learn how interfaces in C# enable types to implement standard functionality, such as IComparable for sorting, enhancing code flexibility and reusability.

Interfaces are a way to implement standard functionality and connect different types to make new things. Think of them like the studs on top of LEGO bricks, which allow them to “stick” together, or electrical standards for plugs and sockets. If a type implements an interface, it promises to the rest of .NET that it supports specific functionality. Therefore, they are sometimes described as contracts.

Press + to interact
Class implements interface
Class implements interface

Common interfaces

Here are some common interfaces that your types might implement:

Interface

Method(s)

Description

IComparable

CompareTo(other)

This defines a comparison method that a type implements to order or sort its instances.

IComparer

Compare(first, second)

This defines a comparison method that a secondary type implements to order or sort instances of a primary type.

IDisposable

Dispose()

This defines a disposal method to release unmanaged resources more efficiently than waiting for a finalizer.

IFormattable

ToString(format, culture)

This defines a culture-aware method to format the value of an object into a string representation.

IFormatter

Serialize(stream, object)

Deserialize(stream)

This defines methods to convert an object to and from a stream of bytes for storage or transfer.

IFormatProvider

GetFormat(type)

This defines a method to format inputs based on a language and region.

Comparing objects when sorting

One of the most common interfaces we want to implement is IComparable. It has one method named CompareTo. It has two variations:

  1. One that works with a nullable object type.

  2. Second that works with a nullable generic type T, as shown in the following code:

Press + to interact
namespace System
{
public interface IComparable
{
int CompareTo(object? obj);
}
public interface IComparable<in T>
{
int CompareTo(T? other);
}
}
...