Jan. 26, 2011, 3 a.m.
posted by freeheart
Two useful static methods from Figure that deserve a closer look are Sort( ) and Reverse( ). These methods do what you think they would: Reverse( ) reverses the order of elements in the array, and Sort( ) sorts the elements in order. These are fully supported for arrays of the built-in C# types, such as string, so sorting an array of strings puts the elements in alphabetical order, and sorting an array of ints puts them in numeric order. Making the Sort( ) method work with your own classes is a bit trickier, as you must implement the IComparable interface (see Chapter 13 for more on interfaces). Figure demonstrates the use of these two methods to manipulate String objects.
Using Array.Sort and Array.Reverse
The output looks like this:
Value: Proust Value: Faulkner Value: Mann Value: Hugo Value: Hugo Value: Mann Value: Faulkner Value: Proust Value: We Value: Hold Value: These Value: Truths Value: To Value: Be Value: Self Value: Evident Value: Be Value: Evident Value: Hold Value: Self Value: These Value: To Value: Truths Value: We
The example begins by creating myArray, an array of strings with the words:
"Proust", "Faulkner", "Mann", "Hugo"
This array is printed, and then passed to the Array.Reverse( ) method, where it is printed again to see that the array itself has been reversed:
Value: Hugo Value: Mann Value: Faulkner Value: Proust
Similarly, the example creates a second array, myOtherArray, containing the words:
"We", "Hold", "These", "Truths", "To", "Be", "Self", "Evident",
Value: Be Value: Evident Value: Hold Value: Self Value: These Value: To Value: Truths Value: We