The Array Class


One very useful class in System is Array. Array is a base class for all arrays in C#. Thus, its methods can be applied to arrays of any of the built-in types or to arrays of types that you create. Array defines the properties shown in Table 20-11. It defines the methods shown in Table 20-12. Notice that C# 2.0 adds several new methods, most of which are generic.

Table 20-11: Properties Defined by Array

Property

Meaning

public bool IsFixedSize { get; }

A read-only property that is true if the array is of fixed size and false if the array is dynamic.

public bool IsReadOnly { get; }

A read-only property that is true if the Array object is read-only and false if it is not.

public bool IsSynchronized { get; }

A read-only property that is true if the array is safe for use in a multithreaded environment and false if it is not.

public int Length { get; }

An int read-only property that contains the number of elements in the array.

public long LongLength { get; }

A long read-only property that contains the number of elements in the array.

public int Rank { get; }

A read-only property that contains the number of dimensions in the array.

public object SyncRoot { get; }

A read-only property that contains the object that synchronizes access to the array.

Table 20-12: Methods Defined by Array

Method

Meaning

public static ReadOnlyCollection<T> AsReadOnly<T>(T[ ] a)

Returns a read-only collection that wraps the array specified by a. (Added by C# 2.0.)

public static int BinarySearch(Array a, object v)

Searches the array specified by a for the value specified by v. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional.

public static int BinarySearch<T>(T[ ] a, T v)

Searches the array specified by a for the value specified by v. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional. (Added by C# 2.0.)

public static int BinarySearch(Array a, object v, IComparer comp)

Searches the array specified by a for the value specified by v, using the comparison method specified by comp. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional.

public static int BinarySearch<T>(T[ ] a, T v, IComparer<T> comp)

Searches the array specified by a for the value specified by v, using the comparison method specified by comp. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional. (Added by C# 2.0.)

public static int BinarySearch(Array a, int start, int count, object v)

Searches a portion of the array specified by a for the value specified by v. The search begins at the index specified by start and is restricted to count elements. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional.

public static int BinarySearch<T>(T[ ] a, int start, int count, T v)

Searches a portion of the array specified by a for the value specified by v. The search begins at the index specified by start and is restricted to count elements. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional. (Added by C# 2.0.)

public static int BinarySearch(Array a, int start, int count, object v, IComparer comp)

Searches a portion of the array specified by a for the value specified by v, using the comparison method specified by comp. The search begins at the index specified by start and is restricted to count elements. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional.

public static int BinarySearch<T>(T [ ] a, int start, int count, T v, IComparer<T> comp)

Searches a portion of the array specified by a for the value specified by v, using the comparison method specified by comp. The search begins at the index specified by start and is restricted to count elements. Returns the index of the first match. If v is not found, returns a negative value. The array must be sorted and one-dimensional. (Added by C# 2.0.)

public static void Clear(Array a, int start, int count)

Sets the specified elements of a to zero. The elements to be zeroed begin at the index specified by start and run for count elements.

public Clear object Clone( )

Returns a copy of the invoking array. The copy refers to the same elements as does the original. This is called a “shallow copy.” Thus, changes to theelements affect both arrays since they both use the same elements.

public static void ConstrainedCopy(Array source, int srcIdx, Array dest, int destIdx, int count)

Copies count elements from source (beginning at srcIdx) to dest (beginning at destIdx). If both arrays are reference types, then ConstrainedCopy( ) makes a “shallow copy,” which means that both arrays will refer to the same elements. If an error occurs during the copy, dest is unchanged. (Added by C# 2.0.)

public static TTo[ ] ConvertAll<TFrom, TTo>(TFrom[ ] a, Converter<TFrom, TTo> conv)

Converts a from type TFrom to TTo and returns the resulting array. The original array is unaffected. The conversion is performed by the specified converter. (Added by C# 2.0.)

public static void Copy(Array source, Array dest, int count)

Beginning at the start of each array, copies count elements from source to dest. When both arrays are reference types, then Copy( ) makes a “shallow copy,” which means that both arrays will refer to the same elements. If an error occurs during the copy, dest is undefined.

public static void Copy(Array source, Array dest, long count)

Beginning at the start of each array, copies count elements from source to dest. When both arrays are reference types, then Copy( ) makes a “shallow copy,” which means that both arrays will refer to the same elements. If an error occurs during the copy, dest is undefined.

public static void Copy(Array source, int srcStart, Array dest, int destStart, int count)

Copies count elements from source[srcStart] to dest[destStart]. When both arrays are reference types, then Copy( ) makes a “shallow copy,” which means that both arrays will refer to the same elements. If an error occurs during the copy, dest is undefined.

public static void Copy(Array source, long srcStart, Array dest, long destStart, long count)

Copies count elements from source[srcStart] to dest[destStart]. When both arrays are reference types, then Copy( ) makes a “shallow copy,” which means that both arrays will refer to the same elements. If an error occurs during the copy, dest is undefined.

public void CopyTo(Array dest, int start)

Copies the elements of the invoking array to dest, beginning at dest[start].

public void CopyTo(Array dest, long start)

Copies the elements of the invoking array to dest, beginning at dest[start].

public static Array CreateInstance(Type t, int size)

Returns a reference to a one-dimensional array that contains size elements of type t.

public static Array

CreateInstance(Type t, int size1, int size2)

Returns a reference to a size1-by-size2 two-dimensional array. Each element is of type t.

public static Array

CreateInstance(Type t, int size1, int size2, int size3)

Returns a reference to a size1-by-size2-by-size3 three-dimensional array. Each element is of type t.

public static Array

CreateInstance(Type t, params int[ ] sizes)

Returns a reference to a multidimensional array that has the dimensions specified in sizes. Each element is of type t.

public static Array

CreateInstance(Type t, params long[ ] sizes)

Returns a reference to a multidimensional array that has the dimensions specified in sizes. Each element is of type t.

public static Array

CreateInstance(Type t, int[ ] sizes, int[ ] startIndexes)

Returns a reference to a multidimensional array that has the dimensions specified in sizes. Each element is of type t. The starting index of each dimension is specified in startIndexes. Thus, it is possible to create arrays that begin at some index other than zero.

public override bool Equals(object v)

Returns true if the value of the invoking object equals the value of v.

public static bool Exists<T>(T[ ] a, Predicate<T> pred)

Returns true if a contains at least one element that satisfies the predicate specified by pred. Returns false if no element satisfies pred. (Added by C# 2.0.)

public static T Find<T>(T[ ] a, Predicate<T> pred)

Returns the first element in a that satisfies the predicate specified by pred. If no element satisfies pred, then default(T) is returned. (Added by C# 2.0.)

public static T[ ] FindAll<T>(T[ ] a, Predicate<T> pred)

Returns an array that contains all elements in a that satisfy the predicate specified by pred. If no element satisfies pred, then a zero-length array is returned. (Added by C# 2.0.)

public static int FindIndex<T>(T[ ] a, Predicate<T> pred)

Returns the index of the first element in a that satisfies the predicate specified by pred. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static int FindIndex<T>(T[ ] a, int start, Predicate<T> pred)

Returns the index of the first element in a that satisfies the predicate specified by pred. The search begins at a[start]. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static int FindIndex<T>(T[ ] a,int start, int count, Predicate<T> pred)

Returns the index of the first element in a that satisfies the predicate specified by pred. The search begins at a[start] and runs for count elements. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static T FindLast<T>(T[ ] a, Predicate<T> pred)

Returns the last element in a that satisfies the predicate specified by pred. If no element satisfies pred, then default(T) is returned. (Added by C# 2.0.)

public static int FindLastIndex<T>(T[ ] a, Predicate<T> pred)

Returns the index of the last element in a that satisfies the predicate specified by pred. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static int FindLastIndex<T>(T[ ] a, int start, Predicate<T> pred)

Returns the index of the last element in a that satisfies the predicate specified by pred. The search proceeds in reverse order, beginning at a[start] and stopping at a[0]. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static int FindLastIndex<T>(T[ ] a, int start, int count, Predicate<T> pred)

Returns the index of the last element in a that satisfies the predicate specified by pred. The search proceeds in reverse order, beginning at a[start] and running for count elements. If no element satisfies pred, 1 is returned. (Added by C# 2.0.)

public static void ForEach<T>(T[ ] a, Action<T> act)

Applies the method specified by act to each element of a. (Added by C# 2.0.)

public IEnumerator GetEnumerator( )

Returns an enumerator object for the array. An enumerator enables you to cycle through an array. Enumerators are described in Chapter 23.

public int GetLength(int dim)

Returns the length of the specified dimension. The dimension is zero-based; thus, to get the length of the first dimension, pass 0. To obtain the length of the second dimension, pass 1.

public long GetLongLength(int dim)

Returns the length of the specified dimension as a long. The dimension is zero-based; thus, to get the length of the first dimension, pass 0. To obtain the length of the second dimension, pass 1.

public int GetLowerBound(int dim)

Returns the first index of the specified dimension, which is usually zero. The parameter dim is zero-based; thus, to get the start index of the first dimension, pass 0. To obtain the start index of the second dimension, pass 1.

public override int GetHashCode( )

Returns the hash code for the invoking object.

public int GetUpperBound(int dim)

Returns the last index of the specified dimension. The parameter dim is zero-based; thus, to get the last index of the first dimension, pass 0. To obtain the last index of the second dimension, pass 1.

public object GetValue(int idx)

Returns the value of the element at index idx within the invoking array. The array must be one-dimensional.

public object GetValue(long idx)

Returns the value of the element at index idx within the invoking array. The array must be one-dimensional.

public object GetValue(int idx1, int idx2)

Returns the value of the element at [idx1, idx2] within the invoking array. The array must be two-dimensional.

public object GetValue(long idx1, long idx2)

Returns the value of the element at [idx1, idx2] within the invoking array. The array must be two-dimensional.

public object GetValue(int idx1, int idx2, int idx3)

Returns the value of the element at [idx1, idx2, idx3] within the invoking array. The array must be three-dimensional.

public object GetValue(long idx1, long idx2, long idx3)

Returns the value of the element at [idx1, idx2, idx3] within the invoking array. The array must be three-dimensional.

public object GetValue(params int[ ] idxs)

Returns the value of the element at the specified indices within the invoking array. The array must have as many dimensions as idxs has elements.

public object GetValue(params long[ ] idxs)

Returns the value of the element at the specified indices within the invoking array. The array must have as many dimensions as idxs has elements.

public static int IndexOf(Array a, object v)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. Returns 1 if the value is not found. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int IndexOf<T>(T[ ] a, T v)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. Returns 1 if the value is not found. (Added by C# 2.0.)

public static int IndexOf(Array a, object v, int start)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. The search begins at a[start]. Returns 1 if the value is not found. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int IndexOf<T>(T[ ] a, T v, int start)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. The search begins at a[start]. Returns 1 if the value is not found. (Added by C# 2.0.)

public static int IndexOf(Array a, object v, int start, int count)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. The search begins at a[start] and runs for count elements. Returns 1 if the value is not found within the specified range. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int IndexOf<T>(T[ ] a, T v, int start, int count)

Returns the index of the first element within the one-dimensional array a that has the value specified by v. The search begins at a[start] and runs for count elements. Returns 1 if the value is not found within the specified range. (Added by C# 2.0.)

public void Initialize( )

Initializes each element in the invoking array by calling the element’s default constructor. This method can be used only on arrays of value types that have constructors.

public static int LastIndexOf(Array a, object v)

Returns the index of the last element within the one-dimensional array a that has the value specified by v. Returns 1 if the value is not found. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int LastIndexOf<T>(T[ ] a, T v)

Returns the index of the last element within the one-dimensional array a that has the value specified by v. Returns 1 if the value is not found. (Added by C# 2.0.)

public static int LastIndexOf(Array a, object v, int start)

Returns the index of the last element within a range of the one-dimensional array a that has the value specified by v. The search proceeds in reverse order, beginning at a[start] and stopping at a[0]. Returns 1 if the value is not found. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int LastIndexOf<T>(T[ ] a, T v, int start)

Returns the index of the last element within a range of the one-dimensional array a that has the value specified by v. The search proceeds in reverse order, beginning at a[start] and stopping at a[0]. Returns 1 if the value is not found. (Added by C# 2.0.)

public static int LastIndexOf(Array a, object v, int start, int count)

Returns the index of the last element within a range of the one-dimensional array a that has the value specified by v. The search proceeds in reverse order, beginning at a[start] and running for count elements. Returns 1 if the value is not found within the specified range. (If the array has a lower bound other than 0, then the failure value is the lower bound 1.)

public static int LastIndexOf<T>(T[ ] a, T v, int start, int count)

Returns the index of the last element within a range of the one-dimensional array a that has the value specified by v. The search proceeds in reverse order, beginning at a[start] and running for count elements. Returns 1 if the value is not found within the specified range. (Added by C# 2.0.)

public static void Resize<T>(ref T a, int size)

Sets the size of a to size. (Added by C# 2.0.)

public static void Reverse(Array a)

Reverses the elements in a.

public static void Reverse(Array a, int start, int count)

Reverses a range of elements in a. The range reversed begins at a[start] and runs for count elements.

public void SetValue(object v, int idx)

Sets the value of the element at index idx within the invoking array to v. The array must be one-dimensional.

public void SetValue(object v, long idx)

Sets the value of the element at index idx within the invoking array to v. The array must be one-dimensional.

public void SetValue(object v, int idx1, int idx2)

Sets the value of the element at indices [idx1, idx2] within the invoking array to v. The array must be two-dimensional.

public void SetValue(object v, long idx1, long idx2)

Sets the value of the element at indices [idx1, idx2] within the invoking array to v. The array must be two-dimensional.

public void SetValue(object v, int idx1, int idx2, int idx3)

Sets the value of the element at indices [idx1, idx2, idx3] within the invoking array to v. The array must be three-dimensional.

public void SetValue(object v, long idx1, long idx2, long idx3)

Sets the value of the element at indices [idx1, idx2, idx3] within the invoking array to v. The array must be three-dimensional.

public void SetValue(object v, params int[ ] idxs)

Sets the value of the element at the specified indices within the invoking array to v. The array must have as many dimensions as idxs has elements.

public void SetValue(object v, params long[ ] idxs)

Sets the value of the element at the specified indices within the invoking array to v. The array must have as many dimensions as idxs has elements.

public static void Sort(Array a)

Sorts a into ascending order. The array must be one-dimensional.

public static void Sort<T>(T[ ] a)

Sorts a into ascending order. The array must be one-dimensional. (Added by sC# 2.0.)

public static void Sort(Array a, IComparer comp)

Sorts a into ascending order using the comparison method specified by comp. The array must be one-dimensional.

public static void Sort<T>(T[ ] a, Comparison<T> comp)

Sorts a into ascending order using the comparison method specified by comp. (Added by C# 2.0.)

public static void Sort<T>(T[ ] a, IComparer<T> comp)

Sorts a into ascending order using the comparison method specified by comp. (Added by C# 2.0.)

public static void Sort(Array k, Array v)

Sorts a pair of one-dimensional arrays into ascending order. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both arrays are in ascending key order.

public static void Sort<TK, TV>(TK[ ] k, TV[ ] v)

Sorts a pair of one-dimensional arrays into ascending order. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both arrays are in ascending key order. (Added by C# 2.0.)

public static void Sort(Array k, Array v, IComparer comp)

Sorts a pair of one-dimensional arrays into ascending order using the comparison method specified by comp. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both arrays are in ascending key order.

public static void

Sort<TK, TV>(TK[ ] k, TV[ ] v, IComparer<TK> comp)

Sorts a pair of one-dimensional arrays into ascending order using the comparison method specified by comp. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort,both arrays are in ascending key order.

public static void Sort(Array a, int start, int count)

Sorts a range of a into ascending order. The range begins at a[start] and runs for count elements. The array must be one-dimensional.

public static void Sort<T>(T[ ] a, int start, int count)

Sorts a range of a into ascending order. The range begins at a[start] and runs for count elements. The array must be one-dimensional. (Added by C# 2.0.)

public static void Sort(Array a, int start, int count, IComparer comp)

Sorts a range of a into ascending order using the comparison method specified by comp. The range begins at a[start] and runs for count elements. The array must be one-dimensional.

public static void Sort<T>(T[ ] a, int start, int count, IComparer<T> comp)

Sorts a range of a into ascending order using the comparison method specified by comp. The range begins at a[start] and runs for count elements. The array must be one-dimensional. (Added by C# 2.0.)

public static void Sort(Array k, Array v, int start, int count)

Sorts a range within a pair of one-dimensional arrays into ascending order. Within both arrays, the range to sort begins at the index passed in start and runs for count elements. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both ranges are in ascending-key order.

public static void

Sort<TK, TV>(TK[ ] k, TK[ ] v, int start, int count)

Sorts a range within a pair of one-dimensional arrays into ascending order. Within both arrays, the range to sort begins at the index passed in start and runs for count elements. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both ranges are in ascending-key order. (Added by C# 2.0.)

public static void Sort(Array k, Array v, int start, int count, IComparer comp)

Sorts a range within a pair of one-dimensional arrays into ascending order using the comparison method specified by comp. Within both arrays, the range to sort begins at the index passed in start and runs for count elements. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both ranges are in ascending- key order.

public static void

Sort<TK, TV>(TK[ ] k, TV v, int start, int count, IComparer<TK> comp)

Sorts a range within a pair of one-dimensional arrays into ascending order using the comparison method specified by comp. Within both arrays, the range to sort begins at the index passed in start and runs for count elements. The k array contains the sort keys. The v array contains the values linked to those keys. Thus, the two arrays contain key/value pairs. After the sort, both ranges are in ascending-key order. (Added by C# 2.0.)

public static bool

TrueForAll<T>(T[ ] a, Predicate<T> pred)

Returns true if the predicate specified by pred is satisfied by all elements in a. If one or more elements fail to satisfy pred, then false is returned. (Added by C#2.0.)

Array implements the following interfaces: ICloneable, ICollection, IEnumerable, and IList. ICollection, IEnumerable, and IList are defined in the System.Collections namespace and are described in Chapter 23.

Several methods use a parameter of type IComparer. This interface is in System.Collections. It defines a method called Compare( ), which compares the values of two objects. It is shown here:

 int Compare(object v1, object v2)

It returns greater than zero if v1 is greater than v2, less than zero if v1 is less than v2, and zero if the two values are equal. C# 2.0 added a generic form, which is IComparer<T>, which is in System.Collections.Generic. It also defines the Compare( ) method and is described in Chapter 23, when generic collections are discussed.

The next few sections demonstrate several commonly used array operations.

Sorting and Searching Arrays

One of the most commonly used array operations is sorting. Because of this, Array supports a rich complement of sorting methods. Using Sort( ), you can sort an entire array, a range within an array, or a pair of arrays that contain corresponding key/value pairs. Once an array has been sorted, you can efficiently search it using BinarySearch( ). Here is a program that demonstrates the Sort( ) and BinarySearch( ) methods by sorting an array of ints:

 // Sort an array and search for a value. using System; class SortDemo {   public static void Main() {     int[] nums = { 5, 4, 6, 3, 14, 9, 8, 17, 1, 24, -1, 0 };     // Display original order.     Console.Write("Original order: ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();     // Sort the array.     Array.Sort(nums);     // Display sorted order.     Console.Write("Sorted order:   ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();     // Search for 14.     int idx = Array.BinarySearch(nums, 14);     Console.WriteLine("Index of 14 is " + idx);   } }

The output is shown here:

 Original order: 5 4 6 3 14 9 8 17 1 24 -1 0 Sorted order:   -1 0 1 3 4 5 6 8 9 14 17 24 Index of 14 is 9

In the preceding example, the array had a base type of int, which is a value type. All methods defined by Array are automatically available to all of the built-in value types. However, this may not be the case for arrays of object references. To sort or search an array of object references, the class type of those objects must implement either the IComparable or IComparable<T> interface. If the class does not implement one of these interfaces, a runtime exception will occur when attempting to sort or search the array. Fortunately, both IComparable and IComparable<T> are easy to implement.

IComparable defines just one method:

 int CompareTo(object obj)

This method compares the invoking object against the value in obj. It returns greater than zero if the invoking object is greater than obj, zero if the two objects are equal, and less than zero if the invoking object is less than obj.

IComparable<T> is the generic version of IComparable. It was added by C# 2.0 and defines the CompareTo( ) method, as shown here:

 int CompareTo(T obj)

The generic version of CompareTo( ) works like the non-generic version, except that the type of data being compared is passed as a type argument to T. The advantage of using IComparable<T> is type-safety because the type of data being operated upon is explicitly specified. Thus, no casts from object are required. For this reason, IComparable<T> is now the preferred interface.

Here is an example that illustrates sorting and searching an array of user-defined class objects:

 // Sort and search an array of objects. using System; class MyClass : IComparable<MyClass> {   public int i;   public MyClass(int x) { i = x; }   // Implement IComparable<MyClass>.   public int CompareTo(MyClass v) {     return i - v.i;   } } class SortDemo {   public static void Main() {     MyClass[] nums = new MyClass[5];     nums[0] = new MyClass(5);     nums[1] = new MyClass(2);     nums[2] = new MyClass(3);     nums[3] = new MyClass(4);     nums[4] = new MyClass(1);     // Display original order.     Console.Write("Original order: ");     foreach(MyClass o in nums)       Console.Write(o.i + " ");     Console.WriteLine();     // Sort the array.     Array.Sort(nums);     // Display sorted order.     Console.Write("Sorted order:   ");     foreach(MyClass o in nums)       Console.Write(o.i + " ");     Console.WriteLine();     // Search for MyClass(2).     MyClass x = new MyClass(2);     int idx = Array.BinarySearch(nums, x);     Console.WriteLine("Index of MyClass(2) is " + idx);   } }

The output is shown here:

 Original order: 5 2 3 4 1 Sorted order:   1 2 3 4 5 Index of MyClass(2) is 1

Reversing an Array

Sometimes it is useful to reverse the contents of an array. For example, you might want to change an array that has been sorted into ascending order into one sorted in descending order. Reversing an array is easy: simply call Reverse( ). Using Reverse( ), you can reverse all or part of an array. The following program demonstrates the process:

 // Reverse an array. using System; class ReverseDemo {   public static void Main() {     int[] nums = { 1, 2, 3, 4, 5 };     // Display original order.     Console.Write("Original order: ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();     // Reverse the entire array.     Array.Reverse(nums);     // Display reversed order.     Console.Write("Reversed order: ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();     // Reverse a range.     Array.Reverse(nums, 1, 3);     // Display reversed order.     Console.Write("Range reversed: ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();   } }

The output is shown here:

 Original order: 1 2 3 4 5 Reversed order: 5 4 3 2 1 Range reversed: 5 2 3 4 1

Copying an Array

Copying all or part of one array to another is another common array operation. To copy an array, use Copy( ). Copy( ) can put elements at the start of the destination array or into the middle, depending upon which version of Copy( ) you use. Copy( ) is demonstrated by the following program:

 // Copy an array. using System; class CopyDemo {   public static void Main() {     int[] source = { 1, 2, 3, 4, 5 };     int[] target = { 11, 12, 13, 14, 15 };     int[] source2 = { -1, -2, -3, -4, -5 };     // Display source.     Console.Write("source: ");     foreach(int i in source)       Console.Write(i + " ");     Console.WriteLine();     // Display original target.     Console.Write("Original contents of target: ");     foreach(int i in target)       Console.Write(i + " ");     Console.WriteLine();     // Copy the entire array.     Array.Copy(source, target, source.Length);     // Display copy.     Console.Write("target after copy:  ");     foreach(int i in target)       Console.Write(i + " ");     Console.WriteLine();     // Copy into middle of target.     Array.Copy(source2, 2, target, 3, 2);     // Display copy.     Console.Write("target after copy:  ");     foreach(int i in target)       Console.Write(i + " ");     Console.WriteLine();   } }

The output is shown here:

 source: 1 2 3 4 5 Original contents of target: 11 12 13 14 15 target after copy:  1 2 3 4 5 target after copy:  1 2 3 -3 -4

Using a Predicate

C# 2.0 introduced a new feature: the predicate. A predicate is a delegate of type System.Predicate that returns either true or false, based upon some condition. It is declared as shown here:

 public delegate bool Predicate<T> (T obj)

The object to be tested against the condition is passed in obj. If obj satisfies that condition, the predicate must return true. Otherwise, it must return false. Predicates are used by several new methods added to Array by C# 2.0, including Exists( ), Find( ), FindIndex( ), and FindAll( ).

The following program demonstrates using a predicate to determine if an array of integers contains a negative value. If a negative value is found, the program then obtains the first negative value in the array. To accomplish this, the program uses Exists( ) and Find( ).

 // Demonstrate Predicate delegate. using System; class PredDemo {   // A predicate method.   // Returns true if v is negative.   static bool isNeg(int v) {     if(v < 0) return true;     return false;   }   public static void Main() {     int[] nums = { 1, 4, -1, 5, -9 };     Console.Write("Contents of nums: ");     foreach(int i in nums)       Console.Write(i + " ");     Console.WriteLine();     // First see if nums contains a negative value.     if(Array.Exists(nums, PredDemo.isNeg)) {       Console.WriteLine("nums contains a negative value.");       // Now, find first negative value.       int x = Array.Find(nums, PredDemo.isNeg);       Console.WriteLine("First negative value is: " + x);     }     else       Console.WriteLine("nums contains no negative values.");   } }

The output is shown here:

 Contents of nums: 1 4 -1 5 -9 nums contains a negative value. First negative value is: -1

In the program, the method passed to Exists( ) and Find( ) for the predicate is isNeg( ). Notice that isNeg( ) is declared like this:

 static bool isNeg(int v) {

The methods Exists( ) and Find( ) will automatically pass the elements of the array (in sequence) to v. Thus, each time isNeg( ) is called, v will contain the next element in the array.

Using an Action

Another new feature introduced by C# 2.0 is the System.Action delegate. An Action is used by another new C# feature, Array.ForEach( ), to perform an action on each element of an array. Action is declared as shown here:

 public delegate void Action<T> (T obj)

The object to be acted upon is passed in obj. When used with ForEach( ), each element of the array is passed to obj in turn. Thus, through the use of ForEach( ) and Action, you can, in a single statement, perform an operation over an entire array.

The following program demonstrates both ForEach( ) and Action. It first creates an array of MyClass objects, then uses the method show( ) to display the values. Next, it uses neg( ) to negate the values. Finally, it uses show( ) again to display the negated values. These operations all occur through calls to ForEach( ).

 // Demonstrate an Action using System; class MyClass {   public int i;   public MyClass(int x) { i = x; } } class ActionDemo {   // An Action method.   // Displays the value it is passed.   static void show(MyClass o) {     Console.Write(o.i + " ");   }   // Another Action method.   // Negates the value it is passed.   static void neg(MyClass o) {     o.i = -o.i;   }   public static void Main() {     MyClass[] nums = new MyClass[5];     nums[0] = new MyClass(5);     nums[1] = new MyClass(2);     nums[2] = new MyClass(3);     nums[3] = new MyClass(4);     nums[4] = new MyClass(1);     Console.Write("Contents of nums: ");     // Use action to show the values.     Array.ForEach(nums, ActionDemo.show);     Console.WriteLine();     // Use action to negate the values.     Array.ForEach(nums, ActionDemo.neg);     Console.Write("Contents of nums negated: ");     // Use action to negate the values again.     Array.ForEach(nums, ActionDemo.show);     Console.WriteLine();   } }

The output is shown here:

 Contents of nums: 5 2 3 4 1 Contents of nums negated: -5 -2 -3 -4 -1




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net