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