3.6. Making a Type Searchable


You have a data type that will be stored as elements in an array or an ArrayList. You would like to use the Array.BinarySearch and ArrayList.BinarySearch methods to allow for custom searching of your data types in the array.


Use the IComparable and IComparer interfaces. The Square class, from Recipe 3.5, implements these in a way so that the Array, ArrayList, and SortedList objects can sort and search an array or collection of Square objects.


By implementing the IComparable interface on your class (or structure), you can take advantage of the search routines of the Array, ArrayList, and SortedList classes. The algorithms for searching are built into these classes; all you have to do is tell them how to search through your classes via the code you implement in the IComparable.CompareTo method.

To implement the CompareTo method, see Recipe 3.5.

The Array and ArrayList classes provide a BinarySearch method to perform a search on the elements in that array. The elements are compared against an object passed to the BinarySearch method in the object parameter. The SortedList class does not have a BinarySearch method; instead, it has Contains, ContainsKey, and ContainsValue methods to perform a linear search when searching for values. This linear search uses the Equals method of the elements in the SortedList collection to do its work (to overload the Equals method, see Recipe 3.9), the Compare and CompareTo methods do not ...

Get C# Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.