2. When the app executes, another compiler (known as the just-in-time compiler
21.3 Class Array and Enumerators
Chapter 8 presented basic array-processing capabilities. All arrays implicitly inherit from
abstractbase classArray(namespaceSystem); this class defines propertyLength, which specifies the number of elements in the array. In addition, classArrayprovidesstatic methods that provide algorithms for processing arrays. Typically, classArray overloads these methods—for example,ArraymethodReversecan reverse the order of the elements in an entire array or can reverse the elements in a specified range of elements in an array.
For a complete list of classArray’sstaticmethods visit:
Figure 21.3 demonstrates severalstaticmethods of classArray.
msdn.microsoft.com/en-us/library/system.array.aspx
1 // Fig. 21.3: UsingArray.cs
2 // Array class static methods for common array manipulations.
3 using System;
4 using System.Collections;
5
6 // demonstrate algorithms of class Array 7 public class UsingArray
8 {
9 private static int[] intValues = { 1, 2, 3, 4, 5, 6 };
10 private static double[] doubleValues = { 8.4, 9.3, 0.2, 7.9, 3.4 };
11 private static int[] intValuesCopy;
12
13 // method Main demonstrates class Array's methods 14 public static void Main( string[] args )
15 {
16 intValuesCopy = new int[ intValues.Length ]; // defaults to zeroes 17
18 Console.WriteLine( "Initial array values:\n" );
19 PrintArrays(); // output initial array contents 20
21 // sort doubleValues 22
23
24 // copy intValues into intValuesCopy 25
26
27 Console.WriteLine( "\nArray values after Sort and Copy:\n" );
28 PrintArrays(); // output array contents 29 Console.WriteLine();
30
31 // search for 5 in intValues 32
33 if ( result >= 0 )
34 Console.WriteLine( "5 found at element {0} in intValues",
35 result );
36 else
37 Console.WriteLine( "5 not found in intValues" );
38
Fig. 21.3 | Arrayclass used to perform common array manipulations. (Part 1 of 2.)
Array.Sort( doubleValues );
Array.Copy( intValues, intValuesCopy, intValues.Length );
int result = Array.BinarySearch( intValues, 5 );
21.3 ClassArrayand Enumerators 819
39 // search for 8763 in intValues 40
41 if ( result >= 0 )
42 Console.WriteLine( "8763 found at element {0} in intValues",
43 result );
44 else
45 Console.WriteLine( "8763 not found in intValues" );
46 } // end Main 47
48 // output array content with enumerators 49 private static void PrintArrays()
50 {
51 Console.Write( "doubleValues: " );
52
53 // iterate through the double array with an enumerator 54
55 56 57 58
59 Console.Write( "\nintValues: " );
60
61 // iterate through the int array with an enumerator 62
63 64 65 66
67 Console.Write( "\nintValuesCopy: " );
68
69 // iterate through the second int array with a foreach statement 70
71 72
73 Console.WriteLine();
74 } // end method PrintArrays 75 } // end class UsingArray
Initial array values:
doubleValues: 8.4 9.3 0.2 7.9 3.4 intValues: 1 2 3 4 5 6
intValuesCopy: 0 0 0 0 0 0 Array values after Sort and Copy:
doubleValues: 0.2 3.4 7.9 8.4 9.3 intValues: 1 2 3 4 5 6
intValuesCopy: 1 2 3 4 5 6 5 found at element 4 in intValues 8763 not found in intValues
Fig. 21.3 | Arrayclass used to perform common array manipulations. (Part 2 of 2.)
result = Array.BinarySearch( intValues, 8763 );
IEnumerator enumerator = doubleValues.GetEnumerator();
while ( enumerator.MoveNext() )
Console.Write( enumerator.Current + " " );
enumerator = intValues.GetEnumerator();
while ( enumerator.MoveNext() )
Console.Write( enumerator.Current + " " );
foreach ( var element in intValuesCopy ) Console.Write( element + " " );
Theusingdirectives in lines 3–4 include the namespacesSystem(for classesArray andConsole) and System.Collections (for interface IEnumerator, which we discuss shortly). References to the assemblies for these namespaces areimplicitlyincluded in every app, so we do not need to add any new references to the project file.
Our test class declares threestaticarray variables (lines 9–11). The first two lines ini- tializeintValuesanddoubleValuesto anintanddoublearray, respectively.staticvari- ableintValuesCopyis intended to demonstrate theArray’sCopymethod, so it’s left with the default valuenull—it does not yet refer to an array.
Line 16 initializesintValuesCopyto anintarray with the same length as arrayint-
Values. Line 19 calls thePrintArraysmethod (lines 49–74) to output the initial contents of all three arrays. We discuss thePrintArraysmethod shortly. We can see from the output of Fig. 21.3 that each element of arrayintValuesCopyis initialized to the default value0. ArrayMethodSort
Line 22 usesstatic ArraymethodSortto sort arraydoubleValues. When this method returns, the array contains its original elements sorted inascendingorder. The elements in the array must implement theIComparableinterface.
ArrayMethodCopy
Line 25 usesstatic ArraymethodCopyto copy elements from arrayintValuesto array
intValuesCopy. The first argument is the array to copy (intValues), the second argument is the destination array (intValuesCopy) and the third argument is anintrepresenting the number of elements to copy (in this case,intValues.Lengthspecifies all elements).
ArrayMethodBinarySearch
Lines 32 and 40 invokestatic ArraymethodBinarySearchto perform binary searches on arrayintValues. MethodBinarySearchreceives thesortedarray in which to search and the key for which to search. The method returns the index in the array at which it finds the key (or a negative number if the key was not found).BinarySearchassumes that it receives a sorted array. Its behavior on anunsortedarray isunpredictable. Chapter 18 dis- cusses binary searching in detail.
ArrayMethodGetEnumeratorand InterfaceIEnumerator
MethodPrintArrays(lines 49–74) uses classArray’s methods to loop though each array.
TheGetEnumeratormethod (line 54) obtains an enumerator for arraydoubleValues. Re- call thatArrayimplements theIEnumerableinterface. All arrays inherit implicitly from
Array, so both theint[] anddouble[] array types implementIEnumerable interface methodGetEnumerator, which returns an enumerator that caniterateover the collection.
InterfaceIEnumerator(which all enumerators implement) defines methodsMoveNextand
Resetand propertyCurrent.MoveNextmoves the enumerator to the next element in the collection. The first call toMoveNextpositions the enumerator at the first element of the collection.MoveNextreturnstrueif there’s at least one more element in the collection;
otherwise, the method returnsfalse. MethodResetpositions the enumerator before the first element of the collection. Methods MoveNext and Reset throw an Invalid-
OperationExceptionif the contents of the collection are modified in any way after the enumerator is created. PropertyCurrentreturns the object at the current location in the collection.