C# Array Class
The Array class is the base class of all arrays in C#; it is defined in the System namespace. The Array class provides various properties and methods for arrays.
The Array class in C# is the base class of all arrays, located under the System namespace.
An array is a collection used to store a fixed size of elements of the same type. Understanding the features and methods of the Array class is important for writing efficient C# programs.
The following is a detailed introduction to the C# Array class, including its features, common methods, properties, and usage examples.
Feature
- Type Safety: an array can only store elements of a specified type, which is determined at declaration time.
- Fixed length: the length of an array cannot be changed after creation.
- Index access: elements in an array are accessed by index, starting from 0.
- Multi-dimensional support: C# supports one-dimensional, multi-dimensional, and jagged arrays (arrays of arrays).
Properties of the Array class
The following table lists some of the most commonly used properties of the Array class:
| Attribute name | Description | Example Code | Output |
|---|---|---|---|
| Length | Gets the total number of elements in the array. | int[] arr = {1, 2, 3}; |
|
int length = arr.Length; |
3 |
||
| Rank | Gets the number of dimensions of the array (that is, the rank of the array). | int[,] matrix = new int[2, 3]; |
|
int rank = matrix.Rank; |
2 |
||
| IsFixedSize | Determines whether the array has a fixed size. | int[] arr = {1, 2, 3}; |
|
bool fixedSize = arr.IsFixedSize; |
true |
||
| IsReadOnly | Determines whether the array is read-only. | int[] arr = {1, 2, 3}; |
|
bool readOnly = arr.IsReadOnly; |
false |
||
| IsSynchronized | Determines whether the array is thread-safe. | int[] arr = {1, 2, 3}; |
|
bool sync = arr.IsSynchronized; |
false |
||
| SyncRoot | Gets the object used to synchronize access to the array, typically used for multi-threaded operations. | int[] arr = {1, 2, 3}; |
|
object syncRoot = arr.SyncRoot; |
syncRoot |
For the complete list of properties of the Array class, please refer to Microsoft's C# documentation.
Methods of the Array class
The following table lists some of the most commonly used methods of the Array class:
| No. | Method & Description |
|---|---|
| 1 | Clear |
| Sets a range of elements in the array to zero, to false, or to null, depending on the element type. | |
| 2 | Copy(Array, Array, Int32) |
| Copies a range of elements starting from the first element of the array to the first element position of another array. The length is specified by a 32-bit integer. | |
| 3 | CopyTo(Array, Int32) |
| Copies all elements from the current one-dimensional array to a specified index position of a specified one-dimensional array. The index is specified by a 32-bit integer. | |
| 4 | **GetLength ** |
| Gets a 32-bit integer representing the total number of elements in the array at the specified dimension. | |
| 5 | GetLongLength |
| Gets a 64-bit integer representing the total number of elements in the array at the specified dimension. | |
| 6 | GetLowerBound |
| Gets the lower bound of the specified dimension of the array. | |
| 7 | GetType |
| Gets the type of the current instance. Inherited from Object. | |
| 8 | GetUpperBound |
| Gets the upper bound of the specified dimension of the array. | |
| 9 | GetValue(Int32) |
| Gets the value at the specified position in the one-dimensional array. The index is specified by a 32-bit integer. | |
| 10 | IndexOf(Array, Object) |
| Searches for the specified object and returns the index of its first occurrence in the entire one-dimensional array. | |
| 11 | Reverse(Array) |
| Reverses the order of the elements in the entire one-dimensional array. | |
| 12 | SetValue(Object, Int32) |
| Sets the value of the element at the specified position in the one-dimensional array. The index is specified by a 32-bit integer. | |
| 13 | Sort(Array) |
| Sorts the elements in the entire one-dimensional array using the IComparable implementation of each element. | |
| 14 | ToString |
| Returns a string representing the current object. Inherited from Object. |
More method reference descriptions
-
AsReadOnly
(T[])
-
BinarySearch
BinarySearch(Array, Int32, Int32, Object, IComparer): searches for a value in a sorted array, using the specified IComparer interface.BinarySearch(Array, Int32, Int32, Object): searches for a value in a sorted array, using IComparable interface.BinarySearch(Array, Object, IComparer): searches a sorted array, using the specified IComparer interface.BinarySearch(Array, Object): searches a sorted array, using IComparable interface.BinarySearch(T[], Int32, Int32, T, IComparer) : searches for a value within a range of a generic array, using the specified IComparer interface.BinarySearch(T[], Int32, Int32, T) : searches for a value within a range of a generic array, using IComparable interface.BinarySearch(T[], T, IComparer) : searches a sorted generic array, using the specified IComparer interface.BinarySearch(T[], T) : searches a sorted generic array, using IComparable interface.-
Clear
Clear(Array, Int32, Int32): sets the elements within the specified range of the array to their default values.Clear(Array): clears the contents of the array.-
Clone
-
ConstrainedCopy
-
ConvertAll
(TInput[], Converter )
-
Copy
Copy(Array, Array, Int32): copies array elements to the destination array, with the length as a 32-bit integer.Copy(Array, Array, Int64): copies array elements to the destination array, with the length as a 64-bit integer.Copy(Array, Int32, Array, Int32, Int32): copies a specified range of elements from the source array to the destination array.Copy(Array, Int64, Array, Int64, Int64): copies a specified range of elements from the source array to the destination array.CopyTo(Array, Int32): copies the current array to the destination array, specifying the index position in the destination array at which to start.CopyTo(Array, Int64): same as above, with the index as a 64-bit integer.-
CreateInstance
CreateInstance(Type, Int32): creates a one-dimensional array of the specified type and length.CreateInstance(Type, Int32, Int32): creates a two-dimensional array.CreateInstance(Type, Int32, Int32, Int32): creates a three-dimensional array.CreateInstance(Type, Int32[]): creates a multi-dimensional array, using the specified dimensions.CreateInstance(Type, Int64[]): creates a multi-dimensional array, using 64-bit integer dimensions.-
Empty
-
Exists
(T[], Predicate )
-
Fill
(T[], T, Int32, Int32)
Fill(T[], T) : fills all elements of the entire array with a given value.-
Find
Find(T[], Predicate) : searches for the first element that matches a condition and returns it.FindAll(T[], Predicate) : returns all elements that match a condition.FindIndex(T[], Int32, Int32, Predicate) : returns the index of the first element that matches a condition within the specified range of the array.FindIndex(T[], Int32, Predicate) : returns the index of the first element that matches a condition after the specified index.FindIndex(T[], Predicate) : returns the index of the first element that matches a condition.FindLast(T[], Predicate) : returns the last element that matches a condition.FindLastIndex(T[], Int32, Int32, Predicate) : within the specified range of the array, returns the index of the last element that matches a condition.FindLastIndex(T[], Predicate) : returns the index of the last element that matches a condition.-
ForEach
(T[], Action )
-
GetEnumerator()
-
GetLength
GetLength(Int32): gets the number of elements in the specified dimension of the array.-
GetLongLength(Int32)
-
GetLowerBound(Int32)
-
GetUpperBound(Int32)
-
GetValue
GetValue(Int32): gets the value at the specified index in a one-dimensional array.GetValue(Int32, Int32): gets the value at the specified indexes in a two-dimensional array.GetValue(Int32, Int32, Int32): gets the value at the specified indexes in a three-dimensional array.GetValue(Int32[]): gets the value in a multi-dimensional array.-
IndexOf
IndexOf(Array, Object): returns the index of the first occurrence of the specified object.IndexOf(Array, Object, Int32): returns the index of the first occurrence of the specified object within a specific range of the array.IndexOf(Array, Object, Int32, Int32): returns the index of the first occurrence of the specified object within the specified range of the array.-
LastIndexOf
IndexOf, but searches from the end of the array.-
Resize
(T[], Int32)
-
Reverse
Reverse(Array): reverses the order of the elements in the array.Reverse(T[]) : reverses the order of the elements in a generic array.-
SetValue
SetValue(Object, Int32): sets the value at the specified index of the array.SetValue(Object, Int32, Int32): sets the value at the specified position in a two-dimensional array.-
Sort
Sort(Array): sorts the array.Sort(T[], IComparer) : sorts a generic array.-
TrueForAll
(T[], Predicate )
For the complete list of methods of the Array class, please refer to Microsoft's C# documentation.
Example
The following program demonstrates the use of some methods of the Array class:
Example
using
System
;
namespace
ArrayApplication
{
class
MyArray
{
static
void
Main
(
string
[
]
args
)
{
int
[
]
list
=
{
34
,
72
,
13
,
44
,
25
,
30
,
10
}
;
Console
.
Write
(
"Original array: "
)
;
foreach
(
int
i
in
list
)
{
Console
.
Write
(
i
" "
)
;
}
Console
.
WriteLine
(
)
;
// Reverse the array
Array
.
Reverse
(
list
)
;
Console
.
Write
(
"Reversed array: "
)
;
foreach
(
int
i
in
list
)
{
Console
.
Write
(
i
" "
)
;
}
Console
.
WriteLine
(
)
;
// Sort the array
Array
.
Sort
(
list
)
;
Console
.
Write
(
"Sorted array: "
)
;
foreach
(
int
i
in
list
)
{
Console
.
Write
(
i
" "
)
;
}
Console
.
WriteLine
(
)
;
Console
.
ReadKey
(
)
;
}
}
}
When the code above is compiled and executed, it produces the following result:
原始数组: 34 72 13 44 25 30 10
逆转数组: 10 30 25 44 13 72 34
排序数组: 10 13 25 30 34 44 72
Examples of common methods
1. Array.Clear(Array, int index, int length)
Sets the elements within a specified range of the array to the default value of their type.
int[] arr = {1, 2, 3, 4, 5};
Array.Clear(arr, 1, 2); // arr = {1, 0, 0, 4, 5}
** 2. Array.Copy(Array sourceArray, Array destinationArray, int length)**
Copies elements from the source array to the destination array.
int[] source = {1, 2, 3};
int[] destination = new int[3];
Array.Copy(source, destination, 3); // destination = {1, 2, 3}
3. Array.Clone()
Creates a shallow copy of the array.
int[] arr = {1, 2, 3};
int[] clonedArr = (int[])arr.Clone();
4. Array.IndexOf(Array array, object value)
Returns the index of the first occurrence of the specified element in a one-dimensional array.
int[] arr = {1, 2, 3, 2};
int index = Array.IndexOf(arr, 2); // index = 1
5. Array.LastIndexOf(Array array, object value)
Returns the index of the last occurrence of the specified element in a one-dimensional array.
int[] arr = {1, 2, 3, 2};
int lastIndex = Array.LastIndexOf(arr, 2); // lastIndex = 3
6. Array.Reverse(Array array)
Reverses the order of the elements in a one-dimensional array.
int[] arr = {1, 2, 3};
Array.Reverse(arr); // arr = {3, 2, 1}
7. Array.Sort(Array array)
Sorts the elements of a one-dimensional array in ascending order.
int[] arr = {3, 1, 2};
Array.Sort(arr); // arr = {1, 2, 3}
8. Array.BinarySearch(Array array, object value)
Searches for an element in a sorted one-dimensional array and returns its index.
int[] arr = {1, 2, 3, 4, 5};
int index = Array.BinarySearch(arr, 3); // index = 2
**Note:** before using BinarySearch, the array must be sorted.
9. Array.Resize
Resizes a one-dimensional array.
int[] arr = {1, 2, 3};
Array.Resize(ref arr, 5); // arr = {1, 2, 3, 0, 0}
10. Array.Exists
Determines whether the array contains any elements that match a condition.
int[] arr = {1, 2, 3};
bool exists = Array.Exists(arr, x => x == 2); // exists = true
11. Array.Find
Finds the first element in the array that matches a condition.
int[] arr = {1, 2, 3, 4};
int result = Array.Find(arr, x => x > 2); // result = 3
12. Array.FindAll
Finds all elements in the array that match a condition.
int[] arr = {1, 2, 3, 4};
int[] results = Array.FindAll(arr, x => x > 2); // results = {3, 4}
13. Array.FindIndex
Returns the index of the first element that matches a condition.
int[] arr = {1, 2, 3, 4};
int index = Array.FindIndex(arr, x => x > 2); // index = 2
14. Array.FindLast
Finds the last element that matches a condition.
int[] arr = {1, 2, 3, 4};
int result = Array.FindLast(arr, x => x > 2); // result = 4
15. Array.FindLastIndex
Returns the index of the last element that matches a condition.
int[] arr = {1, 2, 3, 4};
int index = Array.FindLastIndex(arr, x => x > 2); // index = 3
16. Array.TrueForAll
Determines whether all elements in the array satisfy a condition.
int[] arr = {1, 2, 3};
bool allPositive = Array.TrueForAll(arr, x => x > 0); // allPositive = true
17. Array.ForEach
Performs the specified action on each element of the array.
int[] arr = {1, 2, 3};
Array.ForEach(arr, x => Console.WriteLine(x)); // 输出 1 2 3
** 18. Array.ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)**
Copies some elements of one array to another and ensures that no data corruption occurs if the copy fails.
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
Array.ConstrainedCopy(source, 0, destination, 0, 5);
19. Array.Fill
Sets all elements of the array to the specified value.
int[] arr = new int[5];
Array.Fill(arr, 10); // arr = {10, 10, 10, 10, 10}
20. Array.AsReadOnly
Returns a read-only wrapper of the array.
int[] arr = {1, 2, 3};
var readOnlyArr = Array.AsReadOnly(arr);
// readOnlyArr[0] = 5; // Compilation error, the collection is read-only
Example
using
System
;
class
Program
{
static
void
Main
(
)
{
// Create and initialize the array
int
[
]
numbers
=
{
5
,
2
,
8
,
1
,
3
}
;
// Sort the array
Array
.
Sort
(
numbers
)
;
// numbers = {1, 2, 3, 5, 8}
// Find element
int
index
=
Array
.
BinarySearch
(
numbers,
5
)
;
// index = 3
// Reverse the array
Array
.
Reverse
(
numbers
)
;
// numbers = {8, 5, 3, 2, 1}
// Check whether there are elements greater than 6
bool
exists
=
Array
.
Exists
(
numbers, x
=>
x
6
)
;
// exists = true
// Multiply the array elements by 2
Array
.
ForEach
(
numbers, x
=>
Console
.
WriteLine
(
x
2
)
)
;
// Resize the array
Array
.
Resize
(
ref
numbers,
7
)
;
// numbers = {8, 5, 3, 2, 1, 0, 0}
// Fill the new elements
Array
.
Fill
(
numbers,
10
,
5
,
2
)
;
// Set the 2 elements starting from index 5 to 10
// numbers = {8, 5, 3, 2, 1, 10, 10}
}
}
C# Arrays