Search⌘ K
AI Features

Implementing Interfaces: Comparing Objects When Sorting

Explore how to implement the IComparable interface in C# to enable sorting of custom object types. Understand the CompareTo method, handle null values, and create a sorting logic using object properties like Name. This lesson helps you ensure your types can be sorted in arrays and collections effectively.

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.

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