Interfaces are a way of connecting different types together to make new things. Think of them like the studs on top of LEGO™ bricks that allow them to "stick" together, or electrical standards for plugs and sockets.
If a type implements an interface, then it is making a promise to the rest of .NET that it supports a certain feature.
Here are some common interfaces that your types might want to 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. |
One of the most common interfaces that you will want to implement is IComparable
. It allows arrays and collections of your type to be sorted.
Add the following code to the Main
method, which creates an array of Person
instances, outputs the array, attempts to sort it, and then outputs the sorted array:
Person[] people = { new Person { Name = "Simon" }, new Person { Name = "Jenny" }, new Person { Name = "Adam" }, new Person { Name = "Richard" } }; WriteLine("Initial list of people:"); foreach (var person in people) { WriteLine($"{person.Name}"); } WriteLine("Use Person's sort implementation:"); Array.Sort(people); foreach (var person in people) { WriteLine($"{person.Name}"); }
Run the application, and you will see this runtime error:
Unhandled Exception: System.InvalidOperationException: Failed to
compare two elements in the array. ---> System.ArgumentException: At
least one object must implement IComparable.
As the error explains, to fix the problem, our type must implement IComparable
.
In the Ch07_PacktLibrary
project, in the Person
class, add the following code to the end of the class definition:
public partial class Person : IComparable<Person>
Visual Studio 2017 and Visual Studio Code will draw a red squiggle under the new code to warn you that you have not yet implemented the method you have promised to.
Visual Studio 2017 and Visual Studio Code can write the skeleton implementation for you if you click on the lightbulb and choose the option Implement interface, as shown in the following screenshot:
Scroll down to find the method that was written for you and delete the statement that throws the NotImplementedException
error. Modify the method to look like this. Visual Studio Code users must write the whole method themselves:
public int CompareTo(Person other) { return Name.CompareTo(other.Name); }
I have chosen to compare two Person
instances by comparing their name fields. People will, therefore, be sorted alphabetically by their name.
Run the application. This time it works:
Initial list of people: Simon Jenny Adam Richard Use Person's sort implementation: Adam Jenny Richard Simon
Sometimes, you won't have access to the source code for a type, and it might not implement the IComparable
interface. Luckily, there is another way to sort instances of a type. You can create a secondary type that implements a slightly different interface, named IComparer
.
In the Ch07_PacktLibrary
project, add a new class named PersonComparer
that implements the IComparer
interface, as shown in the following block of code. It will compare two people by comparing the length of their Name
field, or if the names are the same length, then by comparing the names alphabetically:
using System.Collections.Generic; namespace Packt.CS7 { public class PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { int temp = x.Name.Length.CompareTo(y.Name.Length); if (temp == 0) { return x.Name.CompareTo(y.Name); } else { return temp; } } } }
In the Main
method, add the following code:
WriteLine("Use PersonComparer's sort implementation:"); Array.Sort(people, new PersonComparer()); foreach (var person in people) { WriteLine($"{person.Name}"); }
Run the application. This time, when we sort the people array, we explicitly ask the sorting algorithm to use the PersonComparer
type instead, so the people are sorted with the shortest names first, and when the lengths of two or more names are equal, to sort them alphabetically:
Use Person's sort implementation: Adam Jenny Richard Simon Use PersonComparer's sort implementation: Adam Jenny Simon Richard
18.226.104.27