Information Technology Reference
In-Depth Information
Example Using the IComparable Interface
To understand what this means and why it's useful, let's start by taking a look at the following
code, which takes an unsorted array of integers and sorts them in ascending order.
￿
The first line creates an array of five integers that are in no particular order.
The second line uses the static Sort method of the Array class to sort the elements.
￿
￿The foreach loop prints them out, showing that the integers are now in ascending order.
int[] MyInt = new int[5] { 20, 4, 16, 9, 2 }; // Create an array of ints.
Array.Sort(MyInt); // Sort elements by magnitude.
foreach (int i in MyInt) // Print them out.
Console.Write("{0} ", i);
This code produces the following output:
2 4 9 16 20
The Sort method works great on an array of int s, but what would happen if you were to try
to use it on one of your own classes, as shown here?
class MyClass // Declare a simple class.
{
public int TheValue;
}
...
MyClass[] mc= new MyClass[5]; // Create an array of five elements.
... // Create and initialize the elements.
Array.Sort(mc); // Try to use Sort--raises exception
When you try to run this code, it raises an exception. So why did it work for an array of int s,
but not for an array of MyClass objects?
The reason Sort doesn't work with the array of user-defined objects is that it relies on the
objects in the array to implement interface IComparable . When Sort is running, it compares
one element of the array to another by calling the element's CompareTo method and passing in
as a parameter a reference to the other element.
The int type implements IComparable , but MyClass does not, so when Sort tries to call the
nonexistent CompareTo method of MyClass , it raises an exception.
Search WWH ::




Custom Search