
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
284
|
Chapter 5: Collections
or you can write your own reversal method:
public static void DoReversal<T>(T[] theArray)
{
T tempHolder = default(T);
if (theArray.Length > 0)
{
for (int counter = 0; counter < (theArray.Length / 2); counter++)
{
tempHolder = theArray[counter];
theArray[counter] = theArray[theArray.Length - counter - 1];
theArray[theArray.Length - counter - 1] = tempHolder;
}
}
else
{
Trace.WriteLine("Nothing to reverse");
}
}
While there is more code to write, the benefit of the DoReversal<T> method is that it
is about twice as fast as the
Array.Reverse method. In addition, you can tailor the
DoReversal<T> method to a specific situation. For example, the DoReversal<T>
method accepts a value type array (int), whereas the Array.Reverse method accepts
only a reference type (
System.Array). This means that a boxing operation will occur
for the
int value types. The DoReversal<T> method removes any boxing operations.
Discussion
The following TestArrayReversal method creates a test array of five integers and dis-
plays the elements in their initial order. Next, the
DoReversal<T> method is called to
reverse the elements in the array. After this method returns, the array is then dis-
played a second time as a reversed array:
public static void TestArrayReversal( )
{
int[] someArray = new ...