System.Array Class

Assembly: Mscorlib.dll
Namespace: System
Summary
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.
C# Syntax:
[Serializable]
public abstract class Array : ICloneable, IList, ICollection, IEnumerable
Thread Safety
Public static (non-instance) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe.

This implementation does not provide a synchronized (thread-safe) wrapper for an Array; however, .NET Framework classes based on Array provide their own synchronized version of the collection using the Array.SyncRoot property.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Remarks
The Array class is the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should use the array constructs provided by the language.

An element is a value in an Array. The length of an Array is the total number of elements it can contain. The rank of an Array is the number of dimensions in the Array. The lower bound of a dimension of an Array is the starting index of that dimension of the Array; a multidimensional Array can have different bounds for each dimension.

Type objects provide information about array type declarations. Array objects with the same array type share the same Type object.

Type.IsArray and Type.GetElementType might not return the expected results with Array because if an array is cast to the type Array, the result is an object, not an array. That is, typeof(System.Array).IsArray returns false, and typeof(System.Array).GetElementType returns null.

Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

The Array.Copy method copies elements not only between arrays of the same type but also between standard arrays of different types; it handles type casting automatically.

Example
The following code example shows how Array.Copy copies elements between an array of type integer and an array of type Object.
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new integer array and a new Object array.
       int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 };
       Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 };
 
       // Prints the initial values of both arrays.
       Console.WriteLine( "Initially," );
       Console.Write( "integer array:" );
       PrintValues( myIntArray );
       Console.Write( "Object array: " );
       PrintValues( myObjArray );
 
       // Copies the first two elements from the integer array to the Object array.
       Array.Copy( myIntArray, myObjArray, 2 );
 
       // Prints the values of the modified arrays.
       Console.WriteLine( "\nAfter copying the first two elements of the integer array to the Object array," );
       Console.Write( "integer array:" );
       PrintValues( myIntArray );
       Console.Write( "Object array: " );
       PrintValues( myObjArray );
 
       // Copies the last two elements from the Object array to the integer array.
       Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 );
 
       // Prints the values of the modified arrays.
       Console.WriteLine( "\nAfter copying the last two elements of the Object array to the integer array," );
       Console.Write( "integer array:" );
       PrintValues( myIntArray );
       Console.Write( "Object array: " );
       PrintValues( myObjArray );
    }
 
 
    public static void PrintValues( Object[] myArr )  {
       foreach ( Object i in myArr )  {
          Console.Write( "\t{0}", i );
       }
       Console.WriteLine();
    }
 
    public static void PrintValues( int[] myArr )  {
       foreach ( int i in myArr )  {
          Console.Write( "\t{0}", i );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Initially,
 integer array:  1       2       3       4       5
 Object array:   26      27      28      29      30

 After copying the first two elements of the integer array to the Object array,
 integer array:  1       2       3       4       5
 Object array:   1       2       28      29      30

 After copying the last two elements of the Object array to the integer array,
 integer array:  1       2       3       29      30
 Object array:   1       2       28      29      30
 */

    

The following code example creates and initializes an Array and displays its properties and its elements.

 public class SamplesArray2{
 
    public static void Main()  {
 
       // Creates and initializes a new three-dimensional Array of type Int32.
       Array myArr = Array.CreateInstance( typeof(Int32), 2, 3, 4 );
       for ( int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++ )
          for ( int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1); j++ )
             for ( int k = myArr.GetLowerBound(2); k <= myArr.GetUpperBound(2); k++ )  {
                myArr.SetValue( (i*100)+(j*10)+k, i, j, k );
             }
 
       // Displays the properties of the Array.
       Console.WriteLine( "The Array has {0} dimension(s) and a total of {1} elements.", myArr.Rank, myArr.Length );
       Console.WriteLine( "\tLength\tLower\tUpper" );
       for ( int i = 0; i < myArr.Rank; i++ )  {
          Console.Write( "{0}:\t{1}", i, myArr.GetLength(i) );
          Console.WriteLine( "\t{0}\t{1}", myArr.GetLowerBound(i), myArr.GetUpperBound(i) );
       }
 
       // Displays the contents of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintValues( myArr );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The Array has 3 dimension(s) and a total of 24 elements.
     Length    Lower    Upper
 0:    2    0    1
 1:    3    0    2
 2:    4    0    3
 The Array contains the following values:
     0    1    2    3
     10    11    12    13
     20    21    22    23
     100    101    102    103
     110    111    112    113
     120    121    122    123
 */

    
See also:
System Namespace | Array.Copy | Object | Type

System.Array Member List:

Public Properties
IsFixedSize Read-only

Gets a value indicating whether the Array has a fixed size.
IsReadOnly Read-only

Gets a value indicating whether the Array is read-only.
IsSynchronized Read-only

Gets a value indicating whether access to the Array is synchronized (thread-safe).
Length Read-only

Gets the total number of elements in all the dimensions of the Array.
Rank Read-only

Gets the rank (number of dimensions) of the Array.
SyncRoot Read-only

Gets an object that can be used to synchronize access to the Array.
Public Methods
BinarySearch Overloaded:
BinarySearch(Array array, object value)

Searches an entire one-dimensional sorted Array for a specific element, using the IComparable interface implemented by each element of the Array and by the specified object.
BinarySearch Overloaded:
BinarySearch(Array array, object value, IComparer comparer)

Searches an entire one-dimensional sorted Array for a value, using the specified IComparer interface.
BinarySearch Overloaded:
BinarySearch(Array array, int index, int length, object value)

Searches a section of a one-dimensional sorted Array for a value, using the IComparable interface implemented by each element of the Array and by the specified value.
BinarySearch Overloaded:
BinarySearch(Array array, int index, int length, object value, IComparer comparer)

Searches a section of a one-dimensional sorted Array for a value, using the specified IComparer interface.
Clear Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
Clone Creates a shallow copy of the Array.
Copy Overloaded:
Copy(Array sourceArray, Array destinationArray, int length)

Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element.
Copy Overloaded:
Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)

Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
CopyTo Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.
CreateInstance Overloaded:
CreateInstance(Type elementType, int length)

Creates a one-dimensional Array of the specified Type and length, with zero-based indexing.
CreateInstance Overloaded:
CreateInstance(Type elementType, int[] lengths)

Creates a multidimensional Array of the specified Type and dimension lengths, with zero-based indexing.
CreateInstance Overloaded:
CreateInstance(Type elementType, int length1, int length2)

Creates a two-dimensional Array of the specified Type and dimension lengths, with zero-based indexing.
CreateInstance Overloaded:
CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)

Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.
CreateInstance Overloaded:
CreateInstance(Type elementType, int length1, int length2, int length3)

Creates a three-dimensional Array of the specified Type and dimension lengths, with zero-based indexing.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetEnumerator Returns an IEnumerator for the Array.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLength Gets the number of elements in the specified dimension of the Array.
GetLowerBound Gets the lower bound of the specified dimension in the Array.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
GetUpperBound Gets the upper bound of the specified dimension in the Array.
GetValue Overloaded:
GetValue(int index)

Gets the value at the specified position in the one-dimensional Array.
GetValue Overloaded:
GetValue(int[] indices)

Gets the value at the specified position in the multidimensional Array.
GetValue Overloaded:
GetValue(int index1, int index2)

Gets the value at the specified position in the two-dimensional Array.
GetValue Overloaded:
GetValue(int index1, int index2, int index3)

Gets the value at the specified position in the three-dimensional Array.
IndexOf Overloaded:
IndexOf(Array array, object value)

Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
IndexOf Overloaded:
IndexOf(Array array, object value, int startIndex)

Searches for the specified object and returns the index of the first occurrence within the section of the one-dimensional Array that extends from the specified index to the last element.
IndexOf Overloaded:
IndexOf(Array array, object value, int startIndex, int count)

Searches for the specified object and returns the index of the first occurrence within the section of the one-dimensional Array that starts at the specified index and contains the specified number of elements.
Initialize Initializes every element of the value-type Array by calling the default constructor of the value type.
LastIndexOf Overloaded:
LastIndexOf(Array array, object value)

Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
LastIndexOf Overloaded:
LastIndexOf(Array array, object value, int startIndex)

Searches for the specified object and returns the index of the last occurrence within the section of the one-dimensional Array that extends from the first element to the specified index.
LastIndexOf Overloaded:
LastIndexOf(Array array, object value, int startIndex, int count)

Searches for the specified object and returns the index of the last occurrence within the section of the one-dimensional Array that contains the specified number of elements and ends at the specified index.
Reverse Overloaded:
Reverse(Array array)

Reverses the sequence of the elements in the entire one-dimensional Array.
Reverse Overloaded:
Reverse(Array array, int index, int length)

Reverses the sequence of the elements in a section of the one-dimensional Array.
SetValue Overloaded:
SetValue(object value, int index)

Sets a value to the element at the specified position in the one-dimensional Array.
SetValue Overloaded:
SetValue(object value, int[] indices)

Sets a value to the element at the specified position in the multidimensional Array.
SetValue Overloaded:
SetValue(object value, int index1, int index2)

Sets a value to the element at the specified position in the two-dimensional Array.
SetValue Overloaded:
SetValue(object value, int index1, int index2, int index3)

Sets a value to the element at the specified position in the three-dimensional Array.
Sort Overloaded:
Sort(Array array)

Sorts the elements in an entire one-dimensional Array using the IComparable interface implemented by each element of the Array.
Sort Overloaded:
Sort(Array keys, Array items)

Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable interface implemented by each key.
Sort Overloaded:
Sort(Array array, IComparer comparer)

Sorts the elements in a one-dimensional Array using the specified IComparer interface.
Sort Overloaded:
Sort(Array keys, Array items, IComparer comparer)

Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.
Sort Overloaded:
Sort(Array array, int index, int length)

Sorts the elements in a section of a one-dimensional Array using the IComparable interface implemented by each element of the Array.
Sort Overloaded:
Sort(Array keys, Array items, int index, int length)

Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable interface implemented by each key.
Sort Overloaded:
Sort(Array array, int index, int length, IComparer comparer)

Sorts the elements in a section of a one-dimensional Array using the specified IComparer interface.
Sort Overloaded:
Sort(Array keys, Array items, int index, int length, IComparer comparer)

Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.
Explicit Interface Implementations 
IList.Add Implements IList.Add. Always throws NotSupportedException.
IList.Clear Sets all elements in the Array to zero, to false, or to null, depending on the element type.
IList.Contains Determines whether an element is in the Array.
IList.IndexOf Searches for the specified object and returns the index of the first occurrence within the current one-dimensional instance.
IList.Insert Implements IList.Insert. Always throws NotSupportedException.
IList.Remove Implements IList.Remove. Always throws NotSupportedException.
IList.RemoveAt Implements IList.RemoveAt. Always throws NotSupportedException.

Hierarchy:


System.Array Member Details

Property: IsFixedSize (read-only)
Summary
Gets a value indicating whether the Array has a fixed size.
C# Syntax:
public virtual bool IsFixedSize {get;}
Implements:
IList.IsFixedSize
Remarks
Array implements the Array.IsFixedSize property because it is required by the IList interface.

An array with a fixed size does not allow the addition or removal of elements after the array is created, but it allows the modification of existing elements.

See also:
IList

Return to top


Property: IsReadOnly (read-only)
Summary
Gets a value indicating whether the Array is read-only.
C# Syntax:
public virtual bool IsReadOnly {get;}
Implements:
IList.IsReadOnly
Remarks
Array implements the Array.IsReadOnly property because it is required by the IList interface.

If you require a read-only collection, use a System.Collections class that implements the IList interface.

An array that is read-only does not allow the addition, removal, or modification of elements after the array is created.

See also:
IList | System.Collections

Return to top


Property: IsSynchronized (read-only)
Summary
Gets a value indicating whether access to the Array is synchronized (thread-safe).
C# Syntax:
public virtual bool IsSynchronized {get;}
Implements:
ICollection.IsSynchronized
Remarks
Array implements the Array.IsSynchronized property because it is required by the ICollection interface.

.NET Framework classes based on Array provide their own synchronized version of the collection using the Array.SyncRoot property.

Classes that use arrays can also implement their own synchronization using the Array.SyncRoot property. The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the collection. Note that some implementations of Array.SyncRoot might return the Array itself.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock a collection during the entire enumeration by using the Array.SyncRoot:

              Array myCollection = new int[];
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
Array.SyncRoot | ICollection

Return to top


Property: Length (read-only)
Summary
Gets the total number of elements in all the dimensions of the Array.
C# Syntax:
public int Length {get;}
See also:
ICollection.Count | Array.GetLength | Array.Rank

Return to top


Property: Rank (read-only)
Summary
Gets the rank (number of dimensions) of the Array.
C# Syntax:
public int Rank {get;}
See also:
Array.Length | Array.GetLength

Return to top


Property: SyncRoot (read-only)
Summary
Gets an object that can be used to synchronize access to the Array.
C# Syntax:
public virtual object SyncRoot {get;}
Implements:
ICollection.SyncRoot
Remarks
This property implements the ICollection interface.

.NET Framework classes based on Array provide their own synchronized version of the collection using the Array.SyncRoot property.

Classes that use arrays can also implement their own synchronization using the Array.SyncRoot property. The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the collection. Note that some implementations of Array.SyncRoot might return the Array itself.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock a collection during the entire enumeration by using the Array.SyncRoot:

              Array myCollection = new int[];
               lock( myCollection.SyncRoot ) {
               foreach ( Object item in myCollection ) {
               // Insert your code here.
               }
              }
            
See also:
Array.IsSynchronized

Return to top


Overloaded Method: BinarySearch(
   Array array,
   object value
)
Summary
Searches an entire one-dimensional sorted Array for a specific element, using the IComparable interface implemented by each element of the Array and by the specified object.
C# Syntax:
public static int BinarySearch(
   Array array,
   object value
);
Parameters:

array

The one-dimensional Array to search.

value

The object to search for.

Return Value:
The index of the specified value in the specified array, if value is found.

-or-

A negative number, which is the bitwise complement of the index of the first element that is larger than value, if value is not found and value is less than one or more elements in array.

-or-

A negative number, which is the bitwise complement of (the index of the last element + 1), if value is not found and value is greater than any of the elements in array.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentException Neither value nor the elements of array implement the IComparable interface.

-or-

value is of a type that is not compatible with the elements of array.

InvalidOperationException The comparer throws an exception.
Remarks
Either value or every element of array must implement the IComparable interface, which is used for comparisons. If the elements of array are not already sorted in increasing value according to the IComparable implementation, the result might be incorrect.

Duplicate elements are allowed. If the Array contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

null can always be compared with any other type; therefore, comparisons with null do not generate an exception. When sorting, null is considered to be less than any other object.

If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to a negative result to produce the index of the first element, if any, that is larger than the specified search value.

Example
The following code example shows how to use Array.BinarySearch to locate a specific object in an Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myIntArray = Array.CreateInstance( typeof(Int32), 5 );
       for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ )
          myIntArray.SetValue( i*2, i );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Int32 array contains the following:" );
       PrintValues( myIntArray );
 
       // Locates a specific object that does not exist in the Array.
       Object myObjectOdd = 3;
       FindMyObject( myIntArray, myObjectOdd );
 
       // Locates an object that exists in the Array.
       Object myObjectEven = 6;
       FindMyObject( myIntArray, myObjectEven );
    }
 
    public static void FindMyObject( Array myArr, Object myObject )  {
       int myIndex=Array.BinarySearch( myArr, myObject );
       if ( myIndex < 0 )
          Console.WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex );
       else
          Console.WriteLine( "The object to search for ({0}) is at index {1}.", myObject, myIndex );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The Int32 array contains the following:
     0    2    4    6    8
 The object to search for (3) is not found. The next larger object is at index 2.
 The object to search for (6) is at index 3.
  */

    
See also:
IComparable | Array.Sort

Return to top


Overloaded Method: BinarySearch(
   Array array,
   object value,
   IComparer comparer
)
Summary
Searches an entire one-dimensional sorted Array for a value, using the specified IComparer interface.
C# Syntax:
public static int BinarySearch(
   Array array,
   object value,
   IComparer comparer
);
Parameters:

array

The one-dimensional Array to search.

value

The object to search for.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Return Value:
The index of the specified value in the specified array, if value is found.

-or-

A negative number, which is the bitwise complement of the index of the first element that is larger than value, if value is not found and value is less than one or more elements in array.

-or-

A negative number, which is the bitwise complement of (the index of the last element + 1), if value is not found and value is greater than any of the elements in array.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentException comparer is null, and neither value nor the elements of array implement the IComparable interface.

-or-

comparer is null, and value is of a type that is not compatible with the elements of array.

InvalidOperationException The comparer throws an exception.
Remarks
The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

If comparer is not null, the elements of array are compared to the specified value using the specified IComparer implementation. If the elements of array are not already sorted in increasing value according to comparer, the result might be incorrect.

If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. If the elements of array are not already sorted in increasing value according to the IComparable implementation, the result might be incorrect.

Duplicate elements are allowed. If the Array contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

null can always be compared with any other type; therefore, comparisons with null do not generate an exception. When sorting, null is considered to be less than any other object.

If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to a negative result to produce the index of the first element, if any, that is larger than the specified search value.

See also:
IComparer | IComparable | Array.Sort

Return to top


Overloaded Method: BinarySearch(
   Array array,
   int index,
   int length,
   object value
)
Summary
Searches a section of a one-dimensional sorted Array for a value, using the IComparable interface implemented by each element of the Array and by the specified value.
C# Syntax:
public static int BinarySearch(
   Array array,
   int index,
   int length,
   object value
);
Parameters:

array

The one-dimensional Array to search.

index

The starting index of the range to search.

length

The length of the range to search.

value

The object to search for.

Return Value:
The index of the specified value in the specified array, if value is found.

-or-

A negative number, which is the bitwise complement of the index of the first element that is larger than value, if value is not found and value is less than one or more elements in array.

-or-

A negative number, which is the bitwise complement of (the index of the last element + 1), if value is not found and value is greater than any of the elements in array.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentOutOfRangeException index is less than the lower bound of array.

-or-

length is less than zero.

ArgumentException index and length do not specify a valid range in array.

-or-

Neither value nor the elements of array implement the IComparable interface.

-or-

value is of a type that is not compatible with the elements of array.

InvalidOperationException The comparer throws an exception.
Remarks
Either value or every element of array must implement the IComparable interface, which is used for comparisons. If the elements of array are not already sorted in increasing value according to the IComparable implementation, the result might be incorrect.

Duplicate elements are allowed. If the Array contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

null can always be compared with any other type; therefore, comparisons with null do not generate an exception. When sorting, null is considered to be less than any other object.

If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to a negative result to produce the index of the first element, if any, that is larger than the specified search value.

See also:
IComparable | Array.Sort

Return to top


Overloaded Method: BinarySearch(
   Array array,
   int index,
   int length,
   object value,
   IComparer comparer
)
Summary
Searches a section of a one-dimensional sorted Array for a value, using the specified IComparer interface.
C# Syntax:
public static int BinarySearch(
   Array array,
   int index,
   int length,
   object value,
   IComparer comparer
);
Parameters:

array

The one-dimensional Array to search.

index

The starting index of the range to search.

length

The length of the range to search.

value

The object to search for.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Return Value:
The index of the specified value in the specified array, if value is found.

-or-

A negative number, which is the bitwise complement of the index of the first element that is larger than value, if value is not found and value is less than one or more elements in array.

-or-

A negative number, which is the bitwise complement of (the index of the last element + 1), if value is not found and value is greater than any of the elements in array.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentOutOfRangeException index is less than the lower bound of array.

-or-

length is less than zero.

ArgumentException index and length do not specify a valid range in array.

-or-

comparer is null, and neither value nor the elements of array implement the IComparable interface.

-or-

comparer is null, and value is of a type that is not compatible with the elements of array.

InvalidOperationException The comparer throws an exception.
Remarks
The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

If comparer is not null, the elements of array are compared to the specified value using the specified IComparer implementation. If the elements of array are not already sorted in increasing value according to comparer, the result might be incorrect.

If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. If the elements of array are not already sorted in increasing value according to the IComparable implementation, the result might be incorrect.

Duplicate elements are allowed. If the Array contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

null can always be compared with any other type; therefore, comparisons with null do not generate an exception when using IComparable. When sorting, null is considered to be less than any other object.

If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to a negative result to produce the index of the first element, if any, that is larger than the specified search value.

See also:
IComparer | IComparable | Array.Sort

Return to top


Method: Clear(
   Array array,
   int index,
   int length
)
Summary
Sets a range of elements in the Array to zero, to false, or to null, depending on the element type.
C# Syntax:
public static void Clear(
   Array array,
   int index,
   int length
);
Parameters:

array

The Array whose elements need to be cleared.

index

The starting index of the range of elements to clear.

length

The number of elements to clear.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException index is less than zero.

-or-

length is less than zero.

-or-

The sum of index and length is greater than the size of the Array.

Remarks
Reference-type elements are set to null. Boolean-type elements are set to false. Other value-type elements are set to zero.

This method only clears the values of the elements; it does not delete the elements themselves. An Array has a fixed size; therefore, elements cannot be added or removed.

See also:
ICollection.Count

Return to top


Method: Clone()
Summary
Creates a shallow copy of the Array.
C# Syntax:
public virtual object Clone();
Return Value:
A shallow copy of the Array.
Implements:
ICloneable.Clone
Remarks
A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.

In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.

The clone is of the same Type as the original Array.

Return to top


Overloaded Method: Copy(
   Array sourceArray,
   Array destinationArray,
   int length
)
Summary
Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element.
C# Syntax:
public static void Copy(
   Array sourceArray,
   Array destinationArray,
   int length
);
Parameters:

sourceArray

The Array that contains the data to copy.

destinationArray

The Array that receives the data.

length

The number of elements to copy.

Exceptions
Exception Type Condition
ArgumentNullException sourceArray is null.

-or-

destinationArray is null.

RankException sourceArray and destinationArray have different ranks.
ArrayTypeMismatchException sourceArray and destinationArray are of incompatible types.
InvalidCastException At least one element in sourceArray cannot be cast to the type of destinationArray.
ArgumentOutOfRangeException length is less than zero.
ArgumentException length is greater than the number of elements in sourceArray.

-or-

length is greater than the number of elements in destinationArray.

Remarks
The sourceArray and destinationArray parameters must have the same number of dimensions.

When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end to end. For example, if an array has three rows (or columns) with four elements each, copying six elements from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column).

If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.

This method is equivalent to the standard C/C++ function memmove, not memcpy.

The arrays can be reference-type arrays or value-type arrays. Type downcasting is performed, as required.

An ArrayTypeMismatchException is thrown if the arrays are of incompatible types. Type compatibility is defined as follows:

If every element in sourceArray requires a downcast (for example, from a base class to a derived class or from an interface to an object) and one or more elements cannot be cast to the corresponding type in destinationArray, an InvalidCastException is thrown.

If this method throws an exception while copying, the state of destinationArray is undefined.

Return to top


Overloaded Method: Copy(
   Array sourceArray,
   int sourceIndex,
   Array destinationArray,
   int destinationIndex,
   int length
)
Summary
Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
C# Syntax:
public static void Copy(
   Array sourceArray,
   int sourceIndex,
   Array destinationArray,
   int destinationIndex,
   int length
);
Parameters:

sourceArray

The Array that contains the data to copy.

sourceIndex

The index in the sourceArray at which copying begins.

destinationArray

The Array that receives the data.

destinationIndex

The index in the destinationArray at which storing begins.

length

The number of elements to copy.

Exceptions
Exception Type Condition
ArgumentNullException sourceArray is null.

-or-

destinationArray is null.

RankException sourceArray and destinationArray have different ranks.
ArrayTypeMismatchException sourceArray and destinationArray are of incompatible types.
InvalidCastException At least one element in sourceArray cannot be cast to the type of destinationArray.
ArgumentOutOfRangeException sourceIndex is less than the lower bound of the first dimension of sourceArray.

-or-

destinationIndex is less than the lower bound of the first dimension of destinationArray.

-or-

length is less than zero.

ArgumentException The sum of sourceIndex and length is greater than the number of elements in sourceArray.

-or-

The sum of destinationIndex and length is greater than the number of elements in destinationArray.

Remarks
The sourceArray and destinationArray parameters must have the same number of dimensions.

When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end to end. For example, if an array has three rows (or columns) with four elements each, copying six elements from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column). To start copying from the second element of the third row (or column), srcIndex must be the upper bound of the first row (or column) plus the length of the second row (or column) plus two.

If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.

This method is equivalent to the standard C/C++ function memmove, not memcpy.

The arrays can be reference-type arrays or value-type arrays. Type downcasting is performed, as required.

An ArrayTypeMismatchException is thrown if the arrays are of incompatible types. Type compatibility is defined as follows:

If every element in sourceArray requires a downcast (for example, from a base class to a derived class or from an interface to an object) and one or more elements cannot be cast to the corresponding type in destinationArray, an InvalidCastException is thrown.

If this method throws an exception while copying, the state of destinationArray is undefined.

Example
The following code example shows how to copy from one Array of type Object to another Array of type integer.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array of type Int32.
       Array myIntArray=Array.CreateInstance( Type.GetType("System.Int32"), 5 );
       for ( int i = myIntArray.GetLowerBound(0); i <= myIntArray.GetUpperBound(0); i++ )
          myIntArray.SetValue( i+1, i );
 
       // Creates and initializes a new Array of type Object.
       Array myObjArray = Array.CreateInstance( Type.GetType("System.Object"), 5 );
       for ( int i = myObjArray.GetLowerBound(0); i <= myObjArray.GetUpperBound(0); i++ )
          myObjArray.SetValue( i+26, i );
 
       // Displays the initial values of both arrays.
       Console.WriteLine( "Int32 array:" );
       PrintValues( myIntArray );
       Console.WriteLine( "Object array:" );
       PrintValues( myObjArray );
 
       // Copies the first element from the Int32 array to the Object array.
       Array.Copy( myIntArray, myIntArray.GetLowerBound(0), myObjArray, myObjArray.GetLowerBound(0), 1 );
 
       // Copies the last two elements from the Object array to the Int32 array.
       Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 );
 
       // Displays the values of the modified arrays.
       Console.WriteLine( "Int32 array - Last two elements should now be the same as Object array:" );
       PrintValues( myIntArray );
       Console.WriteLine( "Object array - First element should now be the same as Int32 array:" );
       PrintValues( myObjArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 Int32 array:
     1    2    3    4    5
 Object array:
     26    27    28    29    30
 Int32 array - Last two elements should now be the same as Object array:
     1    2    3    29    30
 Object array - First element should now be the same as Int32 array:
     1    27    28    29    30
 */

    

Return to top


Method: CopyTo(
   Array array,
   int index
)
Summary
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.
C# Syntax:
public virtual void CopyTo(
   Array array,
   int index
);
Parameters:

array

The one-dimensional Array that is the destination of the elements copied from the current Array.

index

The index in array at which copying begins.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException The source Array is multidimensional.

-or-

array is multidimensional.

ArgumentOutOfRangeException index is less than zero.
ArgumentException index is equal to or greater than the length of array.

-or-

The number of elements in the source Array is greater than the available space from index to the end of the destination array.

ArrayTypeMismatchException The type of the source Array cannot be cast automatically to the type of the destination array.
Implements:
ICollection.CopyTo
Remarks
This method supports the ICollection interface. If implementing ICollection is not explicitly required, use Array.Copy to avoid an extra indirection.

If this method throws an exception while copying, the state of array is undefined.

Example
The following code example shows how to copy an Array to another Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes two new Arrays.
       Array mySourceArray=Array.CreateInstance( typeof(String), 6 );
       mySourceArray.SetValue( "three", 0 );
       mySourceArray.SetValue( "napping", 1 );
       mySourceArray.SetValue( "cats", 2 );
       mySourceArray.SetValue( "in", 3 );
       mySourceArray.SetValue( "the", 4 );
       mySourceArray.SetValue( "barn", 5 );
       Array myTargetArray=Array.CreateInstance( typeof(String), 15 );
       myTargetArray.SetValue( "The", 0 );
       myTargetArray.SetValue( "quick", 1 );
       myTargetArray.SetValue( "brown", 2 );
       myTargetArray.SetValue( "fox", 3 );
       myTargetArray.SetValue( "jumped", 4 );
       myTargetArray.SetValue( "over", 5 );
       myTargetArray.SetValue( "the", 6 );
       myTargetArray.SetValue( "lazy", 7 );
       myTargetArray.SetValue( "dog", 8 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The target Array contains the following (before and after copying):" );
       PrintValues( myTargetArray, ' ' );
 
       // Copies the source Array to the target Array, starting at index 6.
       mySourceArray.CopyTo( myTargetArray, 6 );
 
       // Displays the values of the Array.
       PrintValues( myTargetArray, ' ' );
    }
 
 
    public static void PrintValues( Array myArr, char mySeparator )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "{0}{1}", mySeparator, myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
  The target Array contains the following (before and after copying):
  The quick brown fox jumped over the lazy dog      
  The quick brown fox jumped over three napping cats in the barn
 */

    

The following code example shows how to copy an Array to another Array with a nonzero lower bound. Note that the entire source Array is copied, including empty elements that overwrite existing elements in the target Array.

 public class SamplesArray2{
 
    public static void Main()  {
       // Creates and initializes the source Array.
       Array myArrayZero=Array.CreateInstance( typeof(String), 3 );
       myArrayZero.SetValue( "zero", 0 );
       myArrayZero.SetValue( "one", 1 );
 
       // Displays the source Array.
       Console.WriteLine( "The array with lower bound=0 contains:" );
       PrintIndexAndValues( myArrayZero );
 
       // Creates and initializes the target Array.
       int[] myArrLen = { 4 };
       int[] myArrLow = { 2 };
       Array myArrayTwo=Array.CreateInstance( typeof(String), myArrLen, myArrLow );
       myArrayTwo.SetValue( "two", 2 );
       myArrayTwo.SetValue( "three", 3 );
       myArrayTwo.SetValue( "four", 4 );
       myArrayTwo.SetValue( "five", 5 );
 
       // Displays the target Array.
       Console.WriteLine( "The array with lower bound=2 contains:" );
       PrintIndexAndValues( myArrayTwo );
 
       // Copies from the array with lower bound=0 to the array with lower bound=2.
       myArrayZero.CopyTo( myArrayTwo, 3 );
 
       // Displays the modified target Array.
       Console.WriteLine( "\nAfter copying to the target array from index 3:" );
       PrintIndexAndValues( myArrayTwo );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The array with lower bound=0 contains:
     [0]:    zero
     [1]:    one
     [2]:    
 The array with lower bound=2 contains:
     [2]:    two
     [3]:    three
     [4]:    four
     [5]:    five
 
 After copying to the target array from index 3:
     [2]:    two
     [3]:    zero
     [4]:    one
     [5]:
 */

    
See also:
ICollection | Array.Copy

Return to top


Overloaded Method: CreateInstance(
   Type elementType,
   int length
)
Summary
Creates a one-dimensional Array of the specified Type and length, with zero-based indexing.
C# Syntax:
public static Array CreateInstance(
   Type elementType,
   int length
);
Parameters:

elementType

The Type of the Array to create.

length

The size of the Array to create.

Return Value:
A new one-dimensional Array of the specified Type with the specified length, using zero-based indexing.
Exceptions
Exception Type Condition
ArgumentNullException elementType is null.
ArgumentException elementType is not a valid Type.
ArgumentOutOfRangeException length is less than zero.
Remarks
Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

Example
The following code example shows how to create and initialize a one-dimensional Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a one-dimensional Array of type Int32.
       Array my1DArray=Array.CreateInstance( typeof(Int32), 5 );
       for ( int i = my1DArray.GetLowerBound(0); i <= my1DArray.GetUpperBound(0); i++ )
          my1DArray.SetValue( i+1, i );
 
       // Displays the values of the Array.
       Console.WriteLine( "The one-dimensional Array contains the following values:" );
       PrintValues( my1DArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 The one-dimensional Array contains the following values:
     1    2    3    4    5
 */

    

Return to top


Overloaded Method: CreateInstance(
   Type elementType,
   int[] lengths
)
Summary
Creates a multidimensional Array of the specified Type and dimension lengths, with zero-based indexing.
C# Syntax:
public static Array CreateInstance(
   Type elementType,
   int[] lengths
);
Parameters:

elementType

The Type of the Array to create.

lengths

An array that contains the size of each dimension of the Array to create.

Return Value:
A new multidimensional Array of the specified Type with the specified length for each dimension, using zero-based indexing.
Exceptions
Exception Type Condition
ArgumentNullException elementType is null.

-or-

lengths is null.

ArgumentException elementType is not a valid Type.

-or-

The lengths array contains less than one element.

ArgumentOutOfRangeException Any value in lengths is less than zero.
Remarks
Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

The number of elements in the lengths array must equal the number of dimensions in the new Array. Each element of the lengths array must specify the length of the corresponding dimension in the new Array.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

Example
The following code example shows how to create and initialize a multidimensional Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a multidimensional Array of type String.
       int[] myLengthsArray = new int[4] { 2, 3, 4, 5 };
       Array my4DArray=Array.CreateInstance( typeof(String), myLengthsArray );
       for ( int i = my4DArray.GetLowerBound(0); i <= my4DArray.GetUpperBound(0); i++ )
          for ( int j = my4DArray.GetLowerBound(1); j <= my4DArray.GetUpperBound(1); j++ )
             for ( int k = my4DArray.GetLowerBound(2); k <= my4DArray.GetUpperBound(2); k++ )
                for ( int l = my4DArray.GetLowerBound(3); l <= my4DArray.GetUpperBound(3); l++ )  {
                   int[] myIndicesArray = new int[4] { i, j, k, l };
                   my4DArray.SetValue( Convert.ToString(i) + j + k + l, myIndicesArray );
                }
 
       // Displays the values of the Array.
       Console.WriteLine( "The four-dimensional Array contains the following values:" );
       PrintValues( my4DArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 The four-dimensional Array contains the following values:
     0000    0001    0002    0003    0004
     0010    0011    0012    0013    0014
     0020    0021    0022    0023    0024
     0030    0031    0032    0033    0034
     0100    0101    0102    0103    0104
     0110    0111    0112    0113    0114
     0120    0121    0122    0123    0124
     0130    0131    0132    0133    0134
     0200    0201    0202    0203    0204
     0210    0211    0212    0213    0214
     0220    0221    0222    0223    0224
     0230    0231    0232    0233    0234
     1000    1001    1002    1003    1004
     1010    1011    1012    1013    1014
     1020    1021    1022    1023    1024
     1030    1031    1032    1033    1034
     1100    1101    1102    1103    1104
     1110    1111    1112    1113    1114
     1120    1121    1122    1123    1124
     1130    1131    1132    1133    1134
     1200    1201    1202    1203    1204
     1210    1211    1212    1213    1214
     1220    1221    1222    1223    1224
     1230    1231    1232    1233    1234
 */

    

Return to top


Overloaded Method: CreateInstance(
   Type elementType,
   int length1,
   int length2
)
Summary
Creates a two-dimensional Array of the specified Type and dimension lengths, with zero-based indexing.
C# Syntax:
public static Array CreateInstance(
   Type elementType,
   int length1,
   int length2
);
Parameters:

elementType

The Type of the Array to create.

length1

The size of the first dimension of the Array to create.

length2

The size of the second dimension of the Array to create.

Return Value:
A new two-dimensional Array of the specified Type with the specified length for each dimension, using zero-based indexing.
Exceptions
Exception Type Condition
ArgumentNullException elementType is null.
ArgumentException elementType is not a valid Type.
ArgumentOutOfRangeException length1 is less than zero.

-or-

length2 is less than zero.

Remarks
Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

Example
The following code example shows how to create and initialize a two-dimensional Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a two-dimensional Array of type String.
       Array my2DArray=Array.CreateInstance( typeof(String), 2, 3 );
       for ( int i = my2DArray.GetLowerBound(0); i <= my2DArray.GetUpperBound(0); i++ )
          for ( int j = my2DArray.GetLowerBound(1); j <= my2DArray.GetUpperBound(1); j++ )
             my2DArray.SetValue( "abc" + i + j, i, j );
 
       // Displays the values of the Array.
       Console.WriteLine( "The two-dimensional Array contains the following values:" );
       PrintValues( my2DArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 The two-dimensional Array contains the following values:
     abc00    abc01    abc02
     abc10    abc11    abc12
 */

    

Return to top


Overloaded Method: CreateInstance(
   Type elementType,
   int[] lengths,
   int[] lowerBounds
)
Summary
Creates a multidimensional Array of the specified Type and dimension lengths, with the specified lower bounds.
C# Syntax:
public static Array CreateInstance(
   Type elementType,
   int[] lengths,
   int[] lowerBounds
);
Parameters:

elementType

The Type of the Array to create.

lengths

A one-dimensional array that contains the size of each dimension of the Array to create.

lowerBounds

A one-dimensional array that contains the lower bound (starting index) of each dimension of the Array to create.

Return Value:
A new multidimensional Array of the specified Type with the specified length and lower bound for each dimension.
Exceptions
Exception Type Condition
ArgumentNullException elementType is null.

-or-

lengths is null.

-or-

lowerBounds is null.

ArgumentException elementType is not a valid Type.

-or-

The lengths array contains less than one element.

-or-

The lengths and lowerBounds arrays do not contain the same number of elements.

ArgumentOutOfRangeException Any value in lengths is less than zero.
Remarks
Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

The lengths and lowerBounds arrays must have the same number of elements. The number of elements in the lengths array must equal the number of dimensions in the new Array.

Each element of the lengths array must specify the length of the corresponding dimension in the new Array.

Each element of the lowerBounds array must specify the lower bound of the corresponding dimension in the new Array. Generally, the .NET Framework class library and many programming languages do not handle nonzero lower bounds.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

Example
The following code example shows how to create and initialize a multidimensional Array with specified lower bounds.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a multidimensional Array of type String.
       int[] myLengthsArray = new int[2] { 3, 5 };
       int[] myBoundsArray = new int[2] { 2, 3 };
       Array myArray=Array.CreateInstance( typeof(String), myLengthsArray, myBoundsArray );
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          for ( int j = myArray.GetLowerBound(1); j <= myArray.GetUpperBound(1); j++ )  {
             int[] myIndicesArray = new int[2] { i, j };
             myArray.SetValue( Convert.ToString(i) + j, myIndicesArray );
          }
 
       // Displays the lower bounds and the upper bounds of each dimension.
       Console.WriteLine( "Bounds:\tLower\tUpper" );
       for ( int i = 0; i < myArray.Rank; i++ )
          Console.WriteLine( "{0}:\t{1}\t{2}", i, myArray.GetLowerBound(i), myArray.GetUpperBound(i) );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintValues( myArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /* 
 This code produces the following output.
 
 Bounds:    Lower    Upper
 0:    2    4
 1:    3    7
 The Array contains the following values:
     23    24    25    26    27
     33    34    35    36    37
     43    44    45    46    47
 */

    

Return to top


Overloaded Method: CreateInstance(
   Type elementType,
   int length1,
   int length2,
   int length3
)
Summary
Creates a three-dimensional Array of the specified Type and dimension lengths, with zero-based indexing.
C# Syntax:
public static Array CreateInstance(
   Type elementType,
   int length1,
   int length2,
   int length3
);
Parameters:

elementType

The Type of the Array to create.

length1

The size of the first dimension of the Array to create.

length2

The size of the second dimension of the Array to create.

length3

The size of the third dimension of the Array to create.

Return Value:
A new three-dimensional Array of the specified Type with the specified length for each dimension, using zero-based indexing.
Exceptions
Exception Type Condition
ArgumentNullException elementType is null.
ArgumentException elementType is not a valid Type.
ArgumentOutOfRangeException length1 is less than zero.

-or-

length2 is less than zero.

-or-

length3 is less than zero.

Remarks
Unlike most classes, Array provides the Array.CreateInstance method, instead of public constructors, to allow for late bound access.

Reference-type elements are initialized to null. Value-type elements are initialized to zero.

Example
The following code example shows how to create and initialize a three-dimensional Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a three-dimensional Array of type Object.
       Array my3DArray=Array.CreateInstance( typeof(Object), 2, 3, 4 );
       for ( int i = my3DArray.GetLowerBound(0); i <= my3DArray.GetUpperBound(0); i++ )
          for ( int j = my3DArray.GetLowerBound(1); j <= my3DArray.GetUpperBound(1); j++ )
             for ( int k = my3DArray.GetLowerBound(2); k <= my3DArray.GetUpperBound(2); k++ )
                my3DArray.SetValue( "abc" + i + j + k, i, j, k );
 
       // Displays the values of the Array.
       Console.WriteLine( "The three-dimensional Array contains the following values:" );
       PrintValues( my3DArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 The three-dimensional Array contains the following values:
     abc000    abc001    abc002    abc003
     abc010    abc011    abc012    abc013
     abc020    abc021    abc022    abc023
     abc100    abc101    abc102    abc103
     abc110    abc111    abc112    abc113
     abc120    abc121    abc122    abc123
 */

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~Array();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Returns an IEnumerator for the Array.
C# Syntax:
public virtual IEnumerator GetEnumerator();
Return Value:
An IEnumerator for the Array.
Implements:
IEnumerable.GetEnumerator
Remarks
Enumerators only allow reading the data in the collection. Enumerators cannot be used to modify the underlying collection.

Initially, the enumerator is positioned before the first element in the collection. IEnumerator.Reset also brings the enumerator back to this position. At this position, calling IEnumerator.Current throws an exception. Therefore, you must call IEnumerator.MoveNext to advance the enumerator to the first element of the collection before reading the value of IEnumerator.Current.

IEnumerator.Current returns the same object until either IEnumerator.MoveNext or IEnumerator.Reset is called. IEnumerator.MoveNext sets IEnumerator.Current to the next element.

After the end of the collection is passed, the enumerator is positioned after the last element in the collection, and calling IEnumerator.MoveNext returns false. If the last call to IEnumerator.MoveNext returned false, calling IEnumerator.Current throws an exception. To set IEnumerator.Current to the first element of the collection again, you can call IEnumerator.Reset followed by IEnumerator.MoveNext.

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to IEnumerator.MoveNext or IEnumerator.Reset throws an InvalidOperationException. If the collection is modified between IEnumerator.MoveNext and IEnumerator.Current, IEnumerator.Current returns the element that it is set to, even if the enumerator is already invalidated.

The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetLength(
   int dimension
)
Summary
Gets the number of elements in the specified dimension of the Array.
C# Syntax:
public int GetLength(
   int dimension
);
Parameters:

dimension

A zero-based dimension of the Array whose length needs to be determined.

Return Value:
The number of elements in the specified dimension.
Exceptions
Exception Type Condition
IndexOutOfRangeException dimension is less than zero.

-or-

dimension is equal to or greater than Array.Rank.

Remarks
An example of Array.GetLength is GetLength(0) , which returns the number of elements in the first dimension of the Array.
See also:
Array.Length | ICollection.Count | Array.Rank

Return to top


Method: GetLowerBound(
   int dimension
)
Summary
Gets the lower bound of the specified dimension in the Array.
C# Syntax:
public int GetLowerBound(
   int dimension
);
Parameters:

dimension

A zero-based dimension of the Array whose lower bound needs to be determined.

Return Value:
The lower bound of the specified dimension in the Array.
Exceptions
Exception Type Condition
IndexOutOfRangeException dimension is less than zero.

-or-

dimension is equal to or greater than Array.Rank.

Remarks
An example of Array.GetLowerBound is GetLowerBound(0) , which returns the lower bound for the indexes of the first dimension of the Array, and GetLowerBound(Rank - 1) returns the lower bound of the last dimension of the Array.
Example
The following code example uses Array.GetLowerBound and Array.GetUpperBound to initialize two arrays, one-dimensional and multidimensional.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates a new one-dimensional Array of type Int32.
       Array my1DIntArray = Array.CreateInstance( typeof(Int32), 5 );
 
       // Uses GetLowerBound and GetUpperBound in the for loop.
       for ( int i = my1DIntArray.GetLowerBound(0); i <= my1DIntArray.GetUpperBound(0); i++ )
          my1DIntArray.SetValue( i+1, i );
 
       // Displays the bounds and values of the one-dimensional Array.
       Console.WriteLine( "One-dimensional Array:" );
       Console.WriteLine( "Rank\tLower\tUpper" );
       Console.WriteLine( "{0}\t{1}\t{2}", 0, my1DIntArray.GetLowerBound(0), my1DIntArray.GetUpperBound(0) );
       Console.WriteLine( "Values:" );
       PrintValues( my1DIntArray );
       Console.WriteLine();
 
       // Creates a new three-dimensional Array of type Int32.
       Array my3DIntArray = Array.CreateInstance( typeof(Int32), 2, 3, 4 );
 
       // Uses GetLowerBound and GetUpperBound in the for loop.
       for ( int i = my3DIntArray.GetLowerBound(0); i <= my3DIntArray.GetUpperBound(0); i++ )
          for ( int j = my3DIntArray.GetLowerBound(1); j <= my3DIntArray.GetUpperBound(1); j++ )
             for ( int k = my3DIntArray.GetLowerBound(2); k <= my3DIntArray.GetUpperBound(2); k++ )  {
                my3DIntArray.SetValue( (i*100)+(j*10)+k, i, j, k );
             }
 
       // Displays the bounds and values of the multidimensional Array.
       Console.WriteLine( "Multidimensional Array:" );
       Console.WriteLine( "Rank\tLower\tUpper" );
       for ( int i = 0; i < my3DIntArray.Rank; i++ )
          Console.WriteLine( "{0}\t{1}\t{2}", i, my3DIntArray.GetLowerBound(i), my3DIntArray.GetUpperBound(i) );
       Console.WriteLine( "Values:" );
       PrintValues( my3DIntArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 One-dimensional Array:
 Rank    Lower    Upper
 0    0    4
 Values:
     1    2    3    4    5
 
 Multidimensional Array:
 Rank    Lower    Upper
 0    0    1
 1    0    2
 2    0    3
 Values:
     0    1    2    3
     10    11    12    13
     20    21    22    23
     100    101    102    103
     110    111    112    113
     120    121    122    123
*/ 

    
See also:
Array.GetUpperBound | Array.Rank

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetUpperBound(
   int dimension
)
Summary
Gets the upper bound of the specified dimension in the Array.
C# Syntax:
public int GetUpperBound(
   int dimension
);
Parameters:

dimension

A zero-based dimension of the Array whose upper bound needs to be determined.

Return Value:
The upper bound of the specified dimension in the Array.
Exceptions
Exception Type Condition
IndexOutOfRangeException dimension is less than zero.

-or-

dimension is equal to or greater than Array.Rank.

Remarks
An example of Array.GetUpperBound is GetUpperBound(0) , which returns the upper bound for the indexes of the first dimension of the Array and GetUpperBound(Rank - 1) returns the upper bound of the last dimension of the Array.
Example
The following code example uses Array.GetLowerBound and Array.GetUpperBound to initialize two arrays, one-dimensional and multidimensional.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates a new one-dimensional Array of type Int32.
       Array my1DIntArray = Array.CreateInstance( typeof(Int32), 5 );
 
       // Uses GetLowerBound and GetUpperBound in the for loop.
       for ( int i = my1DIntArray.GetLowerBound(0); i <= my1DIntArray.GetUpperBound(0); i++ )
          my1DIntArray.SetValue( i+1, i );
 
       // Displays the bounds and values of the one-dimensional Array.
       Console.WriteLine( "One-dimensional Array:" );
       Console.WriteLine( "Rank\tLower\tUpper" );
       Console.WriteLine( "{0}\t{1}\t{2}", 0, my1DIntArray.GetLowerBound(0), my1DIntArray.GetUpperBound(0) );
       Console.WriteLine( "Values:" );
       PrintValues( my1DIntArray );
       Console.WriteLine();
 
       // Creates a new three-dimensional Array of type Int32.
       Array my3DIntArray = Array.CreateInstance( typeof(Int32), 2, 3, 4 );
 
       // Uses GetLowerBound and GetUpperBound in the for loop.
       for ( int i = my3DIntArray.GetLowerBound(0); i <= my3DIntArray.GetUpperBound(0); i++ )
          for ( int j = my3DIntArray.GetLowerBound(1); j <= my3DIntArray.GetUpperBound(1); j++ )
             for ( int k = my3DIntArray.GetLowerBound(2); k <= my3DIntArray.GetUpperBound(2); k++ )  {
                my3DIntArray.SetValue( (i*100)+(j*10)+k, i, j, k );
             }
 
       // Displays the bounds and values of the multidimensional Array.
       Console.WriteLine( "Multidimensional Array:" );
       Console.WriteLine( "Rank\tLower\tUpper" );
       for ( int i = 0; i < my3DIntArray.Rank; i++ )
          Console.WriteLine( "{0}\t{1}\t{2}", i, my3DIntArray.GetLowerBound(i), my3DIntArray.GetUpperBound(i) );
       Console.WriteLine( "Values:" );
       PrintValues( my3DIntArray );
    }
 
 
    public static void PrintValues( Array myArr )  {
       System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator();
       int i = 0;
       int cols = myArr.GetLength( myArr.Rank - 1 );
       while ( myEnumerator.MoveNext() )  {
          if ( i < cols )  {
             i++;
          } else  {
             Console.WriteLine();
             i = 1;
          }
          Console.Write( "\t{0}", myEnumerator.Current );
       }
       Console.WriteLine();
    }
 }
 /*
 This code produces the following output.
 
 One-dimensional Array:
 Rank    Lower    Upper
 0    0    4
 Values:
     1    2    3    4    5
 
 Multidimensional Array:
 Rank    Lower    Upper
 0    0    1
 1    0    2
 2    0    3
 Values:
     0    1    2    3
     10    11    12    13
     20    21    22    23
     100    101    102    103
     110    111    112    113
     120    121    122    123
*/ 

    
See also:
Array.GetLowerBound | Array.Rank

Return to top


Overloaded Method: GetValue(
   int index
)
Summary
Gets the value at the specified position in the one-dimensional Array.
C# Syntax:
public object GetValue(
   int index
);
Parameters:

index

The position of the Array element to get.

Return Value:
The value at the specified position in the one-dimensional Array.
Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly one dimension.
IndexOutOfRangeException index is outside the range of valid indexes for the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether the value of index is out of bounds.
See also:
Array.GetLowerBound | Array.GetUpperBound | Array.SetValue

Return to top


Overloaded Method: GetValue(
   int[] indices
)
Summary
Gets the value at the specified position in the multidimensional Array.
C# Syntax:
public object GetValue(
   int[] indices
);
Parameters:

indices

A one-dimensional array of indexes that specifies the position of the Array element to get.

Return Value:
The value at the specified position in the multidimensional Array.
Exceptions
Exception Type Condition
ArgumentNullException indices is null.
ArgumentException The number of dimensions in the current Array is not equal to the number of elements in indices.
IndexOutOfRangeException Any element in indices is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The number of elements in indices must equal the number of dimensions in the Array. All elements in the indices array must collectively specify the position of the desired element in the multidimensional Array.

The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.

See also:
Array.GetLowerBound | Array.GetUpperBound | Array.SetValue

Return to top


Overloaded Method: GetValue(
   int index1,
   int index2
)
Summary
Gets the value at the specified position in the two-dimensional Array.
C# Syntax:
public object GetValue(
   int index1,
   int index2
);
Parameters:

index1

The first-dimension index of the Array element to get.

index2

The second-dimension index of the Array element to get.

Return Value:
The value at the specified position in the two-dimensional Array.
Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly two dimensions.
IndexOutOfRangeException Either index1 or index2 is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.
Example
The following code example shows how to use Array.GetValue to get a specific value in the Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myArray=Array.CreateInstance( typeof(String), 2, 4 );
       myArray.SetValue( "The", 0, 0 );
       myArray.SetValue( "quick", 0, 1 );
       myArray.SetValue( "brown", 0, 2 );
       myArray.SetValue( "fox", 0, 3 );
       myArray.SetValue( "jumped", 1, 0 );
       myArray.SetValue( "over", 1, 1 );
       myArray.SetValue( "the", 1, 2 );
       myArray.SetValue( "lazy", 1, 3 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          for ( int j = myArray.GetLowerBound(1); j <= myArray.GetUpperBound(1); j++ )
             Console.WriteLine( "\t[{0},{1}]:\t{2}", i, j, myArray.GetValue( i, j ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array contains the following values:
     [0,0]:    The
     [0,1]:    quick
     [0,2]:    brown
     [0,3]:    fox
     [1,0]:    jumped
     [1,1]:    over
     [1,2]:    the
     [1,3]:    lazy
 */ 

    
See also:
Array.GetLowerBound | Array.GetUpperBound | Array.SetValue

Return to top


Overloaded Method: GetValue(
   int index1,
   int index2,
   int index3
)
Summary
Gets the value at the specified position in the three-dimensional Array.
C# Syntax:
public object GetValue(
   int index1,
   int index2,
   int index3
);
Parameters:

index1

The first-dimension index of the Array element to get.

index2

The second-dimension index of the Array element to get.

index3

The third-dimension index of the Array element to get.

Return Value:
The value at the specified position in the three-dimensional Array.
Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly three dimensions.
IndexOutOfRangeException index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.
See also:
Array.GetLowerBound | Array.GetUpperBound | Array.SetValue

Return to top


Overloaded Method: IndexOf(
   Array array,
   object value
)
Summary
Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
C# Syntax:
public static int IndexOf(
   Array array,
   object value
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

Return Value:
The index of the first occurrence of value within the entire array, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
Remarks
The one-dimensional Array is searched forward starting at the first element and ending at the last element.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the first occurrence of a specified element.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the first occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.IndexOf( myArray, myString );
       Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in the last section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 4 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in a section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 6, 5 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /*
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The first occurrence of "the" is at index 0.
 The first occurrence of "the" between index 4 and the end is at index 6.
 The first occurrence of "the" between index 6 and index 10 is at index 6.
 */

    
See also:
Array.LastIndexOf

Return to top


Overloaded Method: IndexOf(
   Array array,
   object value,
   int startIndex
)
Summary
Searches for the specified object and returns the index of the first occurrence within the section of the one-dimensional Array that extends from the specified index to the last element.
C# Syntax:
public static int IndexOf(
   Array array,
   object value,
   int startIndex
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

startIndex

The starting index of the search.

Return Value:
The index of the first occurrence of value within the section of array that extends from startIndex to the last element, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException startIndex is outside the range of valid indexes for array.
RankException array is multidimensional.
Remarks
The one-dimensional Array is searched forward starting at startIndex and ending at the last element.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the first occurrence of a specified element.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the first occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.IndexOf( myArray, myString );
       Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in the last section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 4 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in a section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 6, 5 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /*
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The first occurrence of "the" is at index 0.
 The first occurrence of "the" between index 4 and the end is at index 6.
 The first occurrence of "the" between index 6 and index 10 is at index 6.
 */

    
See also:
Array.LastIndexOf

Return to top


Overloaded Method: IndexOf(
   Array array,
   object value,
   int startIndex,
   int count
)
Summary
Searches for the specified object and returns the index of the first occurrence within the section of the one-dimensional Array that starts at the specified index and contains the specified number of elements.
C# Syntax:
public static int IndexOf(
   Array array,
   object value,
   int startIndex,
   int count
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

startIndex

The starting index of the search.

count

The number of elements in the section to search.

Return Value:
The index of the first occurrence of value within the section of array that starts at startIndex and contains the number of elements specified in count, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException startIndex is outside the range of valid indexes for array.

-or-

count is less than zero.

-or-

startIndex and count do not specify a valid section in array.

RankException array is multidimensional.
Remarks
The one-dimensional Array is searched forward starting at startIndex and ending at startIndex + count - 1.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the first occurrence of a specified element.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the first occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.IndexOf( myArray, myString );
       Console.WriteLine( "The first occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in the last section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 4 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 4 and the end is at index {1}.", myString, myIndex );
 
       // Searches for the first occurrence of the duplicated value in a section of the Array.
       myIndex = Array.IndexOf( myArray, myString, 6, 5 );
       Console.WriteLine( "The first occurrence of \"{0}\" between index 6 and index 10 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /*
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The first occurrence of "the" is at index 0.
 The first occurrence of "the" between index 4 and the end is at index 6.
 The first occurrence of "the" between index 6 and index 10 is at index 6.
 */

    
See also:
Array.LastIndexOf

Return to top


Method: Initialize()
Summary
Initializes every element of the value-type Array by calling the default constructor of the value type.
C# Syntax:
public void Initialize();
Remarks
This method is designed to help compilers support value-type arrays; most users do not need this method. It must not be used on reference-type arrays.

If the Array is not a value-type Array or if the value type does not have a default constructor, the Array is not modified.

The value-type Array can have any lower bound and any number of dimensions.

You can use this method only on value types that have constructors; however, value types that are native to C# do not have constructors.

Return to top


Overloaded Method: LastIndexOf(
   Array array,
   object value
)
Summary
Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
C# Syntax:
public static int LastIndexOf(
   Array array,
   object value
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

Return Value:
The index of the last occurrence of value within the entire array, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
Remarks
The one-dimensional Array is searched backward starting at the last element and ending at the first element.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the last occurrence of a specified element in an array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the last occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.LastIndexOf( myArray, myString );
       Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in the first section of the Array.
       myIndex = Array.LastIndexOf( myArray, myString, 8 );
       Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in a section of the Array.
       // Note that the start index is greater than the end index because the search is done backward.
       myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
       Console.WriteLine( "The last occurrence of \"{0}\" between index 10 and index 6 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 10 and index 6 is at index 10.
 */

    
See also:
Array.IndexOf

Return to top


Overloaded Method: LastIndexOf(
   Array array,
   object value,
   int startIndex
)
Summary
Searches for the specified object and returns the index of the last occurrence within the section of the one-dimensional Array that extends from the first element to the specified index.
C# Syntax:
public static int LastIndexOf(
   Array array,
   object value,
   int startIndex
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

startIndex

The starting index of the backward search.

Return Value:
The index of the last occurrence of value within the section of array that extends from the first element to startIndex, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException startIndex is outside the range of valid indexes for array.
RankException array is multidimensional.
Remarks
The one-dimensional Array is searched backward starting at startIndex and ending at the first element.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the last occurrence of a specified element in an array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the last occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.LastIndexOf( myArray, myString );
       Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in the first section of the Array.
       myIndex = Array.LastIndexOf( myArray, myString, 8 );
       Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in a section of the Array.
       // Note that the start index is greater than the end index because the search is done backward.
       myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
       Console.WriteLine( "The last occurrence of \"{0}\" between index 10 and index 6 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 10 and index 6 is at index 10.
 */

    
See also:
Array.IndexOf

Return to top


Overloaded Method: LastIndexOf(
   Array array,
   object value,
   int startIndex,
   int count
)
Summary
Searches for the specified object and returns the index of the last occurrence within the section of the one-dimensional Array that contains the specified number of elements and ends at the specified index.
C# Syntax:
public static int LastIndexOf(
   Array array,
   object value,
   int startIndex,
   int count
);
Parameters:

array

The one-dimensional Array to search.

value

The object to locate in array.

startIndex

The starting index of the backward search.

count

The number of elements in the section to search.

Return Value:
The index of the last occurrence of value within the section of array that contains the number of elements specified in count and ends at startIndex, if found; otherwise, the lower bound of the array - 1.
Exceptions
Exception Type Condition
ArgumentNullException array is null.
ArgumentOutOfRangeException startIndex is outside the range of valid indexes for array.

-or-

count is less than zero.

-or-

startIndex and count do not specify a valid section in array.

RankException array is multidimensional.
Remarks
The one-dimensional Array is searched backward starting at startIndex and ending at startIndex - count + 1.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Example
The following code example shows how to determine the index of the last occurrence of a specified element in an array. Note that the Array.LastIndexOf method is a backward search; therefore, count must be less than or equal to (startIndex - the lower bound of the array + 1).
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array with three elements of the same value.
       Array myArray=Array.CreateInstance( typeof(String), 12 );
       myArray.SetValue( "the", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
       myArray.SetValue( "in", 9 );
       myArray.SetValue( "the", 10 );
       myArray.SetValue( "barn", 11 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Searches for the last occurrence of the duplicated value.
       String myString = "the";
       int myIndex = Array.LastIndexOf( myArray, myString );
       Console.WriteLine( "The last occurrence of \"{0}\" is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in the first section of the Array.
       myIndex = Array.LastIndexOf( myArray, myString, 8 );
       Console.WriteLine( "The last occurrence of \"{0}\" between the start and index 8 is at index {1}.", myString, myIndex );
 
       // Searches for the last occurrence of the duplicated value in a section of the Array.
       // Note that the start index is greater than the end index because the search is done backward.
       myIndex = Array.LastIndexOf( myArray, myString, 10, 6 );
       Console.WriteLine( "The last occurrence of \"{0}\" between index 10 and index 6 is at index {1}.", myString, myIndex );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array contains the following values:
     [0]:    the
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
     [9]:    in
     [10]:    the
     [11]:    barn
 The last occurrence of "the" is at index 10.
 The last occurrence of "the" between the start and index 8 is at index 6.
 The last occurrence of "the" between index 10 and index 6 is at index 10.
 */

    
See also:
Array.IndexOf

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: Reverse(
   Array array
)
Summary
Reverses the sequence of the elements in the entire one-dimensional Array.
C# Syntax:
public static void Reverse(
   Array array
);
Parameters:

array

The one-dimensional Array to reverse.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
Remarks
After a call to this method, the element at myArray[i] , where i is any index in the array, moves to myArray[j] , where j equals ( myArray.Length + myArray.GetLowerBound(0) ) - ( i - myArray.GetLowerBound(0) ) - 1 .
Example
The following code example shows how to reverse the sort of the values in an Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myArray=Array.CreateInstance( typeof(String), 9 );
       myArray.SetValue( "The", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array initially contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Reverses the sort of the values of the Array.
       Array.Reverse( myArray );
 
       // Displays the values of the Array.
       Console.WriteLine( "After reversing:" );
       PrintIndexAndValues( myArray );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array initially contains the following values:
     [0]:    The
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
 After reversing:
     [0]:    dog
     [1]:    lazy
     [2]:    the
     [3]:    over
     [4]:    jumped
     [5]:    fox
     [6]:    brown
     [7]:    quick
     [8]:    The
 */ 

    

Return to top


Overloaded Method: Reverse(
   Array array,
   int index,
   int length
)
Summary
Reverses the sequence of the elements in a section of the one-dimensional Array.
C# Syntax:
public static void Reverse(
   Array array,
   int index,
   int length
);
Parameters:

array

The one-dimensional Array to reverse.

index

The starting index of the section to reverse.

length

The number of elements in the section to reverse.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentOutOfRangeException index is less than the lower bound of array.

-or-

length is less than zero.

ArgumentException index and length do not specify a valid range in array.
Remarks
After a call to this method, the element at myArray[i] , where i is any index in the array, moves to myArray[j] , where j equals ( myArray.Length + myArray.GetLowerBound(0) ) - ( i - myArray.GetLowerBound(0) ) - 1 .
Example
The following code example shows how to reverse the sort of the values in a section of an Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myArray=Array.CreateInstance( typeof(String), 9 );
       myArray.SetValue( "The", 0 );
       myArray.SetValue( "QUICK", 1 );
       myArray.SetValue( "BROWN", 2 );
       myArray.SetValue( "FOX", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array initially contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Reverses the sort of the values of the Array.
       Array.Reverse( myArray, 1, 3 );
 
       // Displays the values of the Array.
       Console.WriteLine( "After reversing:" );
       PrintIndexAndValues( myArray );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array initially contains the following values:
     [0]:    The
     [1]:    QUICK
     [2]:    BROWN
     [3]:    FOX
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
 After reversing:
     [0]:    The
     [1]:    FOX
     [2]:    BROWN
     [3]:    QUICK
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
 */ 

    

Return to top


Overloaded Method: SetValue(
   object value,
   int index
)
Summary
Sets a value to the element at the specified position in the one-dimensional Array.
C# Syntax:
public void SetValue(
   object value,
   int index
);
Parameters:

value

The new value for the specified element.

index

The position of the Array element to set.

Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly one dimension.

-or-

value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current Array.

IndexOutOfRangeException index is outside the range of valid indexes for the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether the value of index is out of bounds.

For more information about conversions, see Convert.

See also:
Array.GetLowerBound | Array.GetUpperBound | Array.GetValue

Return to top


Overloaded Method: SetValue(
   object value,
   int[] indices
)
Summary
Sets a value to the element at the specified position in the multidimensional Array.
C# Syntax:
public void SetValue(
   object value,
   int[] indices
);
Parameters:

value

The new value for the specified element.

indices

A one-dimensional array of indexes that specifies the position of the element to set.

Exceptions
Exception Type Condition
ArgumentNullException indices is null.
ArgumentException The number of dimensions in the current Array is not equal to the number of elements in indices.
IndexOutOfRangeException Any element in indices is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The number of elements in indices must equal the number of dimensions in the Array. All elements in the indices array must collectively specify the position of the desired element in the multidimensional Array.

The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the values in the indices array is out of bounds.

For more information about conversions, see Convert.

See also:
Array.GetLowerBound | Array.GetUpperBound | Array.GetValue

Return to top


Overloaded Method: SetValue(
   object value,
   int index1,
   int index2
)
Summary
Sets a value to the element at the specified position in the two-dimensional Array.
C# Syntax:
public void SetValue(
   object value,
   int index1,
   int index2
);
Parameters:

value

The new value for the specified element.

index1

The first-dimension index of the Array element to set.

index2

The second-dimension index of the Array element to set.

Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly two dimensions.

-or-

value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current Array.

IndexOutOfRangeException Either index1 or index2 is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.

For more information about conversions, see Convert.

Example
The following code example shows how to use Array.SetValue to initialize an Array.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myArray=Array.CreateInstance( typeof(String), 2, 4 );
       myArray.SetValue( "The", 0, 0 );
       myArray.SetValue( "quick", 0, 1 );
       myArray.SetValue( "brown", 0, 2 );
       myArray.SetValue( "fox", 0, 3 );
       myArray.SetValue( "jumped", 1, 0 );
       myArray.SetValue( "over", 1, 1 );
       myArray.SetValue( "the", 1, 2 );
       myArray.SetValue( "lazy", 1, 3 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array contains the following values:" );
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          for ( int j = myArray.GetLowerBound(1); j <= myArray.GetUpperBound(1); j++ )
             Console.WriteLine( "\t[{0},{1}]:\t{2}", i, j, myArray.GetValue( i, j ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array contains the following values:
     [0,0]:    The
     [0,1]:    quick
     [0,2]:    brown
     [0,3]:    fox
     [1,0]:    jumped
     [1,1]:    over
     [1,2]:    the
     [1,3]:    lazy
 */ 

    
See also:
Array.GetLowerBound | Array.GetUpperBound | Array.GetValue

Return to top


Overloaded Method: SetValue(
   object value,
   int index1,
   int index2,
   int index3
)
Summary
Sets a value to the element at the specified position in the three-dimensional Array.
C# Syntax:
public void SetValue(
   object value,
   int index1,
   int index2,
   int index3
);
Parameters:

value

The new value for the specified element.

index1

The first-dimension index of the Array element to set.

index2

The second-dimension index of the Array element to set.

index3

The third-dimension index of the Array element to set.

Exceptions
Exception Type Condition
ArgumentException The current Array does not have exactly three dimensions. -or-

value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current Array.

IndexOutOfRangeException index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current Array.
Remarks
The Array.GetLowerBound and Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.

For more information about conversions, see Convert.

See also:
Array.GetLowerBound | Array.GetUpperBound | Array.GetValue

Return to top


Overloaded Method: Sort(
   Array array
)
Summary
Sorts the elements in an entire one-dimensional Array using the IComparable interface implemented by each element of the Array.
C# Syntax:
public static void Sort(
   Array array
);
Parameters:

array

The one-dimensional Array to sort.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
InvalidOperationException The comparer throws an exception.
Remarks
Each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

Example
The following code example shows how to sort the values in an Array. Note that the result might vary depending on the current CultureInfo.
 using System;
 public class SamplesArray  {
 
    public static void Main()  {
 
       // Creates and initializes a new Array.
       Array myArray=Array.CreateInstance( typeof(String), 9 );
       myArray.SetValue( "The", 0 );
       myArray.SetValue( "quick", 1 );
       myArray.SetValue( "brown", 2 );
       myArray.SetValue( "fox", 3 );
       myArray.SetValue( "jumped", 4 );
       myArray.SetValue( "over", 5 );
       myArray.SetValue( "the", 6 );
       myArray.SetValue( "lazy", 7 );
       myArray.SetValue( "dog", 8 );
 
       // Displays the values of the Array.
       Console.WriteLine( "The Array initially contains the following values:" );
       PrintIndexAndValues( myArray );
 
       // Sorts the values of the Array.
       Array.Sort( myArray );
 
       // Displays the values of the Array.
       Console.WriteLine( "After sorting:" );
       PrintIndexAndValues( myArray );
    }
 
 
    public static void PrintIndexAndValues( Array myArray )  {
       for ( int i = myArray.GetLowerBound(0); i <= myArray.GetUpperBound(0); i++ )
          Console.WriteLine( "\t[{0}]:\t{1}", i, myArray.GetValue( i ) );
    }
 }
 /* 
 This code produces the following output.
 
 The Array initially contains the following values:
     [0]:    The
     [1]:    quick
     [2]:    brown
     [3]:    fox
     [4]:    jumped
     [5]:    over
     [6]:    the
     [7]:    lazy
     [8]:    dog
 After sorting:
     [0]:    brown
     [1]:    dog
     [2]:    fox
     [3]:    jumped
     [4]:    lazy
     [5]:    over
     [6]:    quick
     [7]:    the
     [8]:    The
 */

    
See also:
IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array keys,
   Array items
)
Summary
Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable interface implemented by each key.
C# Syntax:
public static void Sort(
   Array keys,
   Array items
);
Parameters:

keys

The one-dimensional Array that contains the keys to sort.

items

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

Exceptions
Exception Type Condition
ArgumentNullException keys is null.
RankException The keys Array is multidimensional.

-or-

The items Array is multidimensional.

ArgumentException items is not null, and the lower bound of keys does not match the lower bound of items.
InvalidOperationException The comparer throws an exception.
Remarks
Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned. Therefore, the items Array is sorted according to the arrangement of the corresponding keys in the keys Array.

Each key in the keys Array must implement the IComparable interface to be capable of comparisons with every other key.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array array,
   IComparer comparer
)
Summary
Sorts the elements in a one-dimensional Array using the specified IComparer interface.
C# Syntax:
public static void Sort(
   Array array,
   IComparer comparer
);
Parameters:

array

The one-dimensional Array to sort.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
InvalidCastException comparer is null, and one or more elements in array do not implement the IComparable interface.
InvalidOperationException The comparer throws an exception.
Remarks
If comparer is null, each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparer | IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array keys,
   Array items,
   IComparer comparer
)
Summary
Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.
C# Syntax:
public static void Sort(
   Array keys,
   Array items,
   IComparer comparer
);
Parameters:

keys

The one-dimensional Array that contains the keys to sort.

items

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Exceptions
Exception Type Condition
ArgumentNullException keys is null.
RankException The keys Array is multidimensional.

-or-

The items Array is multidimensional.

ArgumentException items is not null, and the lower bound of keys does not match the lower bound of items.
InvalidCastException comparer is null, and one or more elements in the keys Array do not implement the IComparable interface.
InvalidOperationException The comparer throws an exception.
Remarks
Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned. Therefore, the items Array is sorted according to the arrangement of the corresponding keys in the keys Array.

If comparer is null, each key in the keys Array must implement the IComparable interface to be capable of comparisons with every other key.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparer | IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array array,
   int index,
   int length
)
Summary
Sorts the elements in a section of a one-dimensional Array using the IComparable interface implemented by each element of the Array.
C# Syntax:
public static void Sort(
   Array array,
   int index,
   int length
);
Parameters:

array

The one-dimensional Array to sort.

index

The starting index of the range to sort.

length

The number of elements in the range to sort.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentOutOfRangeException index is less than the lower bound of array.

-or-

length is less than zero.

ArgumentException index and length do not specify a valid range in array.
InvalidOperationException The comparer throws an exception.
Remarks
Each element within the specified section of array must implement the IComparable interface to be capable of comparisons with every other element in array.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array keys,
   Array items,
   int index,
   int length
)
Summary
Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable interface implemented by each key.
C# Syntax:
public static void Sort(
   Array keys,
   Array items,
   int index,
   int length
);
Parameters:

keys

The one-dimensional Array that contains the keys to sort.

items

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array. -or-

null to sort only the keys Array.

-or-

null to sort only the keys Array.

index

The starting index of the range to sort.

length

The number of elements in the range to sort.

Exceptions
Exception Type Condition
ArgumentNullException keys is null.
RankException The keys Array is multidimensional.

-or-

items is not null and is multidimensional.

ArgumentOutOfRangeException index is less than the lower bound of keys.

-or-

length is less than zero.

ArgumentException items is not null, and the lower bound of keys does not match the lower bound of items.

-or-

index and length do not specify a valid range in the keys Array.

-or-

items is not null, and index and length do not specify a valid range in the items Array.

InvalidOperationException The comparer throws an exception.
Remarks
Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned. Therefore, the items Array is sorted according to the arrangement of the corresponding keys in the keys Array.

Each key within the specified section of the keys Array must implement the IComparable interface to be capable of comparisons with every other key.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array array,
   int index,
   int length,
   IComparer comparer
)
Summary
Sorts the elements in a section of a one-dimensional Array using the specified IComparer interface.
C# Syntax:
public static void Sort(
   Array array,
   int index,
   int length,
   IComparer comparer
);
Parameters:

array

The one-dimensional Array to sort.

index

The starting index of the range to sort.

length

The number of elements in the range to sort.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Exceptions
Exception Type Condition
ArgumentNullException array is null.
RankException array is multidimensional.
ArgumentOutOfRangeException index is less than the lower bound of array.

-or-

length is less than zero.

ArgumentException index and length do not specify a valid range in array.
InvalidCastException comparer is null, and one or more elements in array do not implement the IComparable interface.
InvalidOperationException The comparer throws an exception.
Remarks
If comparer is null, each element within the specified section of array must implement the IComparable interface to be capable of comparisons with every other element in array.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparer | IComparable | Array.BinarySearch

Return to top


Overloaded Method: Sort(
   Array keys,
   Array items,
   int index,
   int length,
   IComparer comparer
)
Summary
Sorts a section of a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer interface.
C# Syntax:
public static void Sort(
   Array keys,
   Array items,
   int index,
   int length,
   IComparer comparer
);
Parameters:

keys

The one-dimensional Array that contains the keys to sort.

items

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

null to sort only the keys Array.

index

The starting index of the range to sort.

length

The number of elements in the range to sort.

comparer

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

The IComparer implementation to use when comparing elements.

-or-

null to use the IComparable implementation of each element.

Exceptions
Exception Type Condition
ArgumentNullException keys is null.
RankException The keys Array is multidimensional.

-or-

items is not null and is multidimensional.

ArgumentOutOfRangeException index is less than the lower bound of keys.

-or-

length is less than zero.

ArgumentException items is not null, and the lower bound of keys does not match the lower bound of items.

-or-

index and length do not specify a valid range in the keys Array.

-or-

items is not null, and index and length do not specify a valid range in the items Array.

InvalidCastException comparer is null, and one or more elements in the keys Array do not implement the IComparable interface.
InvalidOperationException The comparer throws an exception.
Remarks
Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned. Therefore, the items Array is sorted according to the arrangement of the corresponding keys in the keys Array.

If comparer is null, each key within the specified section of the keys Array must implement the IComparable interface to be capable of comparisons with every other key.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n log n) operation, where n is the number of elements to sort.

See also:
IComparer | IComparable | Array.BinarySearch

Return to top


Method: IList.Add(
   object value
)
Summary
Implements IList.Add. Always throws NotSupportedException.
C# Syntax:
int IList.Add(
   object value
);
Parameters:

value

The object to be added to the Array.

Return Value:
An exception is always thrown.
Exceptions
Exception Type Condition
NotSupportedException Always thrown.
Implements:
IList.Add
Remarks
Array has a fixed size; therefore, elements cannot be added or removed. Use Array.SetValue to change the value of an existing element.
See also:
Array.SetValue

Return to top


Method: IList.Clear()
Summary
Sets all elements in the Array to zero, to false, or to null, depending on the element type.
C# Syntax:
void IList.Clear();
Exceptions
Exception Type Condition
NotSupportedException The Array is read-only.

-or-

The Array has a fixed size.

Implements:
IList.Clear
Remarks
Reference-type elements are set to null. Boolean-type elements are set to false. Other value-type elements are set to zero.

This method only clears the values of the elements; it does not delete the elements themselves. Array has a fixed size; therefore, elements cannot be added or removed.

See also:
ICollection.Count

Return to top


Method: IList.Contains(
   object value
)
Summary
Determines whether an element is in the Array.
C# Syntax:
bool IList.Contains(
   object value
);
Parameters:

value

The object to locate in the Array. The element to locate can be null. The object to locate in the Array. The element to locate can be null.

Return Value:
true if value is found in the Array; otherwise, false.
Implements:
IList.Contains
Remarks
This method performs a linear search; therefore, the average execution time is proportional to ICollection.Count. That is, this method is an O(n) operation, where n is ICollection.Count.

This method determines equality by calling Object.Equals.

See also:
Array.IndexOf | Array.LastIndexOf

Return to top


Method: IList.IndexOf(
   object value
)
Summary
Searches for the specified object and returns the index of the first occurrence within the current one-dimensional instance.
C# Syntax:
int IList.IndexOf(
   object value
);
Parameters:

value

The object to locate in the current Array.

Return Value:
The index of the first occurrence of value within the entire Array, if found; otherwise, the lower bound of the Array - 1.
Exceptions
Exception Type Condition
RankException The current Array is multidimensional.
Implements:
IList.IndexOf
Remarks
The one-dimensional Array is searched forward starting at the first element and ending at the last element.

The elements are compared to the specified value using the Object.Equals method. If the element type is a nonintrinsic (user-defined) type, the Equals implementation of that type is used.

Since most arrays will have a lower bound of zero, this method would generally return -1 when value is not found. In the rare case that the lower bound of the array is equal to Int32.MinValue and value is not found, this method returns Int32.MaxValue, which is System.Int32.MinValue - 1 .

Return to top


Method: IList.Insert(
   int index,
   object value
)
Summary
Implements IList.Insert. Always throws NotSupportedException.
C# Syntax:
void IList.Insert(
   int index,
   object value
);
Parameters:

index

The index at which value should be inserted.

value

The object to insert.

Exceptions
Exception Type Condition
NotSupportedException Always thrown.
Implements:
IList.Insert
Remarks
Array has a fixed size; therefore, elements cannot be added or removed. Use Array.SetValue to change the value of an existing element.
See also:
Array.SetValue

Return to top


Method: IList.Remove(
   object value
)
Summary
Implements IList.Remove. Always throws NotSupportedException.
C# Syntax:
void IList.Remove(
   object value
);
Parameters:

value

The object to remove from the Array.

Exceptions
Exception Type Condition
NotSupportedException Always thrown.
Implements:
IList.Remove
Remarks
Array has a fixed size; therefore, elements cannot be added or removed. Use Array.SetValue to change the value of an existing element.
See also:
Array.SetValue

Return to top


Method: IList.RemoveAt(
   int index
)
Summary
Implements IList.RemoveAt. Always throws NotSupportedException.
C# Syntax:
void IList.RemoveAt(
   int index
);
Parameters:

index

The index of the element to remove.

Exceptions
Exception Type Condition
NotSupportedException Always thrown.
Implements:
IList.RemoveAt
Remarks
Array has a fixed size; therefore, elements cannot be added or removed. Use Array.SetValue to change the value of an existing element.
See also:
Array.SetValue

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.