The .NET Array Class
Managed arrays in the .NET Framework all inherit from System::Array, which means that every managed array has a number of useful properties and methods. Array class provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime. The syntax is:
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 employ 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. In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException. 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 a null reference (Nothing in Visual Basic). Unlike most classes, Array provides the 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. Some methods, such as CreateInstance, Copy, CopyTo, GetValue, and SetValue, provide overloads that accept 64-bit integers as parameters to accommodate large capacity arrays. LongLength and GetLongLength return 64-bit integers indicating the length of the array. The Array is not guaranteed to be sorted. You must sort the Array prior to performing operations (such as BinarySearch) that require the Array to be sorted. (Take note that in C++ .NET the dot (.) in the namespaces is replaced with scope operator (::)). |
1. Open Visual C++/Studio if it isn’t already open, and create a new CLR Console Application project named SysArray.
2. Try the following code example that shows how Array::Copy copies elements between an array of type integer and an array of type Object. Use the same project for all the example in this section. Build and run your project.
// SysArray.cpp : main project file.
#include "stdafx.h"
using namespace System;
void myarr();
void PrintValues(array<Object^>^myArr);
void PrintValues(array<int>^myArr);
int main(array<System::String ^> ^args)
{
myarr();
return 0;
}
void myarr()
{
// Creates and initializes a new int array and a new Object array.
array<int>^myIntArray = {1,2,3,4,5};
array<Object^>^myObjArray = {26,27,28,29,30};
// Prints the initial values of both arrays.
Console::WriteLine("Initially..........");
Console::Write("int array: ");
PrintValues(myIntArray);
Console::Write(" and Object array: ");
PrintValues(myObjArray);
// Copies the first two elements from the int 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 int array to the Object array,");
Console::Write("int array: ");
PrintValues(myIntArray);
Console::Write(" and Object array: ");
PrintValues(myObjArray);
// Copies the last two elements from the Object array to the int 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 int array,");
Console::Write("int array: ");
PrintValues(myIntArray );
Console::Write(" and Object array: ");
PrintValues(myObjArray);
}
void PrintValues(array<Object^>^myArr)
{
for (int i = 0; i < myArr->Length; i++)
Console::Write(" {0}", myArr[i]);
Console::WriteLine();
}
void PrintValues(array<int>^myArr)
{
for (int i = 0; i < myArr->Length; i++)
Console::Write(" {0}", myArr[i]);
}
Output:
The following code example creates and initializes an Array and displays its properties and its elements.
// SysArray.cpp : main project file.
#include "stdafx.h"
using namespace System;
void PrintValues(Array^ myarr);
void myarr2();
int main(array<System::String ^> ^args)
{
myarr2();
return 0;
}
void myarr2()
{
// Creates and initializes a new three-dimensional
// Array instance of type Int32.
Array^ myArr = Array::CreateInstance(Int32::typeid, 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 instance has {0} dimension(s) and "
"a total of {1} elements.", myArr->Rank, myArr->Length);
Console::WriteLine();
Console::WriteLine("Length Lower Upper");
for (int i = 0; i < myArr->Rank; i++)
{
Console::Write("{0}: {1}", i, myArr->GetLength(i));
Console::WriteLine(" {0} {1}", myArr->GetLowerBound(i), myArr->GetUpperBound(i));
}
Console::WriteLine();
Console::WriteLine("The Array instance contains the following values:");
Console::WriteLine();
PrintValues(myArr);
}
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("{0}\t", myEnumerator->Current);
}
Console::WriteLine();
}
Output:
Array Members
Array class members provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime. The following tables list the members exposed by the Array type.
Public Properties |
|
Symbol |
|
Name | Description |
IsFixedSize | Gets a value indicating whether the Array has a fixed size. |
IsReadOnly | Gets a value indicating whether the Array is read-only. |
IsSynchronized | Gets a value indicating whether access to the Array is synchronized (thread safe). |
Length | Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. |
LongLength | Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. |
Rank | Gets the rank (number of dimensions) of the Array. |
SyncRoot | Gets an object that can be used to synchronize access to the Array. |
Table 2 |
Public Methods |
|
Symbol |
|
Name | Description |
AsReadOnly | Returns a read-only wrapper for the specified array. |
BinarySearch | Overloaded. Searches a one-dimensional sorted Array for a value, using a binary search algorithm. |
Clear | Sets a range of elements in the Array to zero, to false, or to a null reference (Nothing in Visual Basic), depending on the element type. |
Clone | Creates a shallow copy of the Array. |
ConstrainedCopy | 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. Guarantees that all changes are undone if the copy does not succeed completely. |
ConvertAll | Converts an array of one type to an array of another type. |
Copy | Overloaded. Copies a range of elements in one Array to another Array and performs type casting and boxing as required. |
CopyTo | Overloaded. Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array. |
CreateInstance | Overloaded. Initializes a new instance of the Array class. |
Equals | Overloaded. Determines whether two Object instances are equal. (Inherited from Object.) |
Exists | Determines whether the specified array contains elements that match the conditions defined by the specified predicate. |
Find | Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array. |
FindAll | Retrieves all the elements that match the conditions defined by the specified predicate. |
FindIndex | Overloaded. |
FindLast | Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array. |
FindLastIndex | Overloaded. |
ForEach | Performs the specified action on each element of the specified array. |
GetEnumerator | Returns an IEnumerator for the Array. |
GetHashCode | Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.) |
GetLength | Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array. |
GetLongLength | Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array. |
GetLowerBound | Gets the lower bound of the specified dimension in the Array. |
GetType | Gets the Type of the current instance. (Inherited from Object.) |
GetUpperBound | Gets the upper bound of the specified dimension in the Array. |
GetValue | Overloaded. Gets the value of the specified element in the current Array. |
IndexOf | Overloaded. Returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array. |
Initialize | Initializes every element of the value-type Array by calling the default constructor of the value type. |
LastIndexOf | Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array. |
ReferenceEquals | Determines whether the specified Object instances are the same instance. (Inherited from Object.) |
Resize | Changes the size of an array to the specified new size. |
Reverse | Overloaded. Reverses the order of the elements in a one-dimensional Array or in a portion of the Array. |
SetValue | Overloaded. Sets the specified element in the current Array to the specified value. |
Sort | Overloaded. Sorts the elements in one-dimensional Array objects. |
ToString | Returns a String that represents the current Object. (Inherited from Object.) |
TrueForAll | Determines whether every element in the array matches the conditions defined by the specified predicate. |
Table 3 |
Protected Methods |
|
Symbol |
|
Name | Description |
Finalize | Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection. (Inherited from Object.) |
MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) |
Table 4 |
Explicit Interface Implementations |
|
Symbol |
|
Name | Description |
System.Collections.IList.Add | Implements IList.Add. Throws a NotSupportedException in all cases. |
System.Collections.IList.Clear | Sets all elements in the Array to zero, to false, or to a null reference (Nothing in Visual Basic), depending on the element type. |
System.Collections.IList.Contains | Determines whether an element is in the Array. |
System.Collections.IList.IndexOf | Searches for the specified object and returns the index of the first occurrence within the current one-dimensional instance. |
System.Collections.IList.Insert | Implements IList.Insert. Throws a NotSupportedException in all cases. |
System.Collections.IList.Remove | Implements IList.Remove. Throws a NotSupportedException in all cases. |
System.Collections.IList.RemoveAt | Implements IList.RemoveAt. Throws a NotSupportedException in all cases. |
System.Collections.ICollection.Count | Gets the number of elements contained in the Array. |
System.Collections.IList.Item | Gets or sets the element at the specified index. |
Table 5 |
Note: In C++ .Net the dot operator, . will be changed to the scope operator, ::.