Array Expressions
Besides being an efficient storage construct, arrays have additional functionality that helps make programs more expressive and powerful. The following example shows one such capability:
string[] weekDays = new string[7]; Console.WriteLine("Number of Days: {0}", weekDays.Length); // Number of Days: 7
For C++ Programmers
From the perspective of traditional built-into-the-language arrays, C++ arrays are simply a pointer to a block of memory. This refers to the C++ arrays derived from its C language ancestry. C# arrays have much more functionality.
The C++ STL array class is similar to the C# ArrayList collection class. Both are library classes.
The previous example showed the array's Length property. The array type has many more methods and properties, as shown in Table 3.2.
Table 3.2 C# Array Members
Method/Property |
Description |
---|---|
AsList |
Returns an Ilist representation of the array |
BinarySearch |
Finds a value in a one-dimensional array using a binary search |
Clear |
Cleans out a range of array values by setting them to 0 or null |
Copy |
Copies a range of array elements to another array |
CreateInstance |
Creates a new instance of an array |
IndexOf |
Finds the first occurrence of a value and returns its index |
LastIndexOf |
Finds the last occurrence of a value and returns its index |
Reverse |
Reverses the elements of a one-dimensional array |
Sort |
Sorts a one-dimensional array |
IsReadOnly |
Returns true if read-only |
IsSynchronized |
Returns true if synchronized |
Length |
Returns the number of elements in all dimensions |
Rank |
Returns the number of dimensions |
SyncRoot |
Returns array synchronization object |
Clone |
Performs a shallow copy |
CopyTo |
Copies from one array to another |
Equals |
Compares array references for equality |
GetEnumerator |
Returns an IEnumerator of a one-dimensional array |
GetHashCode |
Returns a unique identifier |
GetLength |
Returns the number of elements in specified dimension |
GetLowerBound |
Returns the lower bound of a dimension |
GetType |
Returns the Type object |
GetUpperBound |
Returns the upper bound of a dimension |
GetValue |
Returns values from specified elements |
Initialize |
Calls the default constructor of each element |
SetValue |
Sets values of specified elements |
ToString |
Returns a string representation |