[Serializable] |
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.
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.
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
*/
| 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. |
| 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. |
| 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. |
| 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:
public virtual bool IsFixedSize {get;}
|
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.
public virtual bool IsReadOnly {get;}
|
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.
public virtual bool IsSynchronized {get;}
|
.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.
}
}
public int Length {get;}
|
public int Rank {get;}
|
public virtual object SyncRoot {get;}
|
.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.
}
}
array
value
-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.
| 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. |
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.
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.
*/
array
value
comparer
-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.
-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.
| 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. |
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.
array
index
length
value
-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.
| 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. |
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.
public static int BinarySearch( |
array
index
length
value
comparer
-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.
-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.
| 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. |
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.
array
index
length
| 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. |
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.
public virtual object Clone(); |
In contrast, a deep copy of an Array copies the elements and everything directly or indirectly referenced by the elements.
sourceArray
destinationArray
length
| 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. |
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.
public static void Copy( |
sourceArray
sourceIndex
destinationArray
destinationIndex
length
| 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. |
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.
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
*/
array
index
| 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. |
If this method throws an exception while copying, the state of array is undefined.
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]:
*/
elementType
length
| Exception Type | Condition |
|---|---|
| ArgumentNullException | elementType is null. |
| ArgumentException | elementType is not a valid Type. |
| ArgumentOutOfRangeException | length is less than zero. |
Reference-type elements are initialized to null. Value-type elements are initialized to zero.
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
*/
elementType
lengths
| 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. |
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.
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
*/
elementType
length1
length2
| 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. |
Reference-type elements are initialized to null. Value-type elements are initialized to zero.
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
*/
elementType
lengths
lowerBounds
| 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. |
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.
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
*/
public static Array CreateInstance( |
elementType
length1
length2
length3
| 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. |
Reference-type elements are initialized to null. Value-type elements are initialized to zero.
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
*/