...
/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.
We'll cover the following...
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.
Common interfaces
Here are some common interfaces that your types might implement:
Interface | Method(s) | Description |
|
| This defines a comparison method that a type implements to order or sort its instances. |
|
| This defines a comparison method that a secondary type implements to order or sort instances of a primary type. |
|
| This defines a disposal method to release unmanaged resources more efficiently than waiting for a finalizer. |
|
| This defines a culture-aware method to format the value of an object into a string representation. |
|
| This defines methods to convert an object to and from a stream of bytes for storage or transfer. |
|
| 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:
One that works with a nullable object type.
Second that works with a nullable generic type
T
, as shown in the following code:
namespace System{public interface IComparable{int CompareTo(object? obj);}public interface IComparable<in T>{int CompareTo(T? other);}}