Csharp Array Class
[ C# Arrays](#)
The Array class is the base class for all arrays in C# and is defined in the System namespace. The Array class provides various properties and methods for working with arrays.
The Array class in C# is the base class for all arrays and is located in the System namespace.
An array is a collection used to store a fixed-size, homogeneous collection of elements. Understanding the features and methods of the Array class is crucial 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.
### Features
* **Type Safety**: Arrays can only store elements of a specified type, which is determined at declaration.
* **Fixed Length**: The length of an array cannot be changed after creation.
* **Index Access**: Elements in an array are accessed via an index, starting from 0.
* **Multi-dimensional Support**: C# supports one-dimensional, multi-dimensional, and jagged arrays (arrays of arrays).
The following table lists some of the most commonly used properties of the Array class:
| Property 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. | `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 an object that can be used to synchronize access to the array, typically for multithreaded operations. | `int[] arr = {1, 2, 3};` `object syncRoot = arr.SyncRoot;` | `syncRoot` |
For a complete list of Array class properties, please refer to the Microsoft C# documentation.
The following table lists some of the most commonly used methods of the Array class:
| Number | 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 from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer. |
| 3 | **CopyTo(Array, Int32)** Copies all the elements of the current one-dimensional array to the specified one-dimensional array starting at the specified destination array index. The index is specified as a 32-bit integer. |
| 4 | **GetLength** Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. |
| 5 | **GetLongLength** Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. |
| 6 | **GetLowerBound** Gets the lower bound of the specified dimension in the Array. |
| 7 | **GetType** Gets the Type of the current instance. Inherited from Object. |
| 8 | **GetUpperBound** Gets the upper bound of the specified dimension in the Array. |
| 9 | **GetValue(Int32)** Gets the value at the specified position in a one-dimensional array. The index is specified as a 32-bit integer. |
| 10 | **IndexOf(Array, Object)** Searches for the specified object and returns the index of the first occurrence within 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 at the specified position in a one-dimensional array. The index is specified as a 32-bit integer. |
| 13 | **Sort(Array)** Sorts the elements in the entire one-dimensional Array using the IComparable implementation of each element of the Array. |
| 14 | **ToString** Returns a string that represents the current object. Inherited from Object. |
### More Method Reference Details
1. **AsReadOnly(T[])**
* Returns a read-only wrapper for the specified array.
2. **BinarySearch**
* `BinarySearch(Array, Int32, Int32, Object, IComparer)`: Searches a range of elements in a sorted Array using the specified `IComparer` interface.
* `BinarySearch(Array, Int32, Int32, Object)`: Searches a range of elements in a sorted Array using the `IComparable` interface.
* `BinarySearch(Array, Object, IComparer)`: Searches a sorted Array using the specified `IComparer` interface.
* `BinarySearch(Array, Object)`: Searches a sorted Array using the `IComparable` interface.
* `BinarySearch(T[], Int32, Int32, T, IComparer)`: Searches a range of elements in a generic Array using the specified `IComparer` interface.
* `BinarySearch(T[], Int32, Int32, T)`: Searches a range of elements in a generic Array using the `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 the `IComparable` interface.
3. **Clear**
* `Clear(Array, Int32, Int32)`: Sets a range of elements in the Array to the default value of each element type.
* `Clear(Array)`: Clears the contents of the array.
4. **Clone**
* Creates a shallow copy of the Array.
5. **ConstrainedCopy**
* Copies a range of elements from the source Array to the destination Array, guaranteeing that if the copy operation succeeds, all changes are committed.
6. **ConvertAll(TInput[], Converter)**
* Converts an array of one type to an array of another type.
7. **Copy**
* `Copy(Array, Array, Int32)`: Copies a specified number of elements from an Array starting at the beginning to another Array starting at the beginning. The length is specified as a 32-bit integer.
* `Copy(Array, Array, Int64)`: Copies a specified number of elements from an Array starting at the beginning to another Array starting at the beginning. The length is specified as a 64-bit integer.
* `Copy(Array, Int32, Array, Int32, Int32)`: Copies a range of elements from a source Array starting at a specified index to a destination Array starting at a specified index.
* `Copy(Array, Int64, Array, Int64, Int64)`: Copies a range of elements from a source Array starting at a specified index to a destination Array starting at a specified index.
* `CopyTo(Array, Int32)`: Copies all the elements of the current array to the specified array starting at the specified destination array index.
* `CopyTo(Array, Int64)`: Same as above, but the index is a 64-bit integer.
8. **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 with the specified lengths.
* `CreateInstance(Type, Int64[])`: Creates a multi-dimensional array with 64-bit integer lengths.
9. **Empty**
* Returns an empty array instance.
10. **Exists(T[], Predicate)**
* Determines whether an array contains elements that match the conditions defined by the specified predicate.
11. **Fill(T[], T, Int32, Int32)**
* Fills the range of elements in the array, specified by start index and count, with the specified value.
* `Fill(T[], T)`: Fills all elements of the array with the specified value.
12. **Find**
* `Find(T[], Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array.
* `FindAll(T[], Predicate)`: Retrieves all the elements that match the conditions defined by the specified predicate.
* `FindIndex(T[], Int32, Int32, Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the Array that starts at the specified index and contains the specified number of elements.
* `FindIndex(T[], Int32, Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the Array that extends from the specified index to the last element.
* `FindIndex(T[], Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array.
* `FindLast(T[], Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array.
* `FindLastIndex(T[], Int32, Int32, Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the Array that starts at the specified index and contains the specified number of elements.
* `FindLastIndex(T[], Predicate)`: Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire Array.
13. **ForEach(T[], Action)**
* Performs the specified action on each element of the specified array.
14. **GetEnumerator()**
* Returns an IEnumerator for the Array.
15. **GetLength**
* `GetLength(Int32)`: Gets an integer that represents the number of elements in the specified dimension of the Array.
16. **GetLongLength(Int32)**
* Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
17. **GetLowerBound(Int32)**
* Gets the lower bound of the specified dimension in the Array.
18. **GetUpperBound(Int32)**
* Gets the upper bound of the specified dimension in the Array.
19. **GetValue**
* `GetValue(Int32)`: Gets the value at the specified position in a one-dimensional array.
* `GetValue(Int32, Int32)`: Gets the value at the specified position in a two-dimensional array.
* `GetValue(Int32, Int32, Int32)`: Gets the value at the specified position in a three-dimensional array.
* `GetValue(Int32[])`: Gets the value at the specified position in a multi-dimensional array.
20. **IndexOf**
* `IndexOf(Array, Object)`: Returns the index of the first occurrence of the specified value in a one-dimensional Array.
* `IndexOf(Array, Object, Int32)`: Returns the index of the first occurrence of the specified value in a one-dimensional Array, starting at the specified index.
* `IndexOf(Array, Object, Int32, Int32)`: Returns the index of the first occurrence of the specified value in a one-dimensional Array, starting at the specified index and searching the specified number of elements.
21. **LastIndexOf**
* Similar to `IndexOf`, but searches from the end of the array.
22. **Resize(T[], Int32)**
* Changes the number of elements of a one-dimensional array to the specified new size.
23. **Reverse**
* `Reverse(Array)`: Reverses the order of the elements in the entire one-dimensional Array.
* `Reverse(T[])`: Reverses the order of the elements in the entire generic Array.
24. **SetValue**
* `SetValue(Object, Int32)`: Sets the value at the specified position in a one-dimensional array.
* `SetValue(Object, Int32, Int32)`: Sets the value at the specified position in a two-dimensional array.
25. **Sort**
* `Sort(Array)`: Sorts the elements in an Array.
* `Sort(T[], IComparer)`: Sorts the elements in a generic Array.
26. **TrueForAll(T[], Predicate)**
* Determines whether every element in the array matches the conditions defined by the specified predicate.
For a complete list of Array class methods, please refer to the Microsoft C# documentation.
The following program demonstrates the usage 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 above code is compiled and executed, it produces the following result:
Original array: 34 72 13 44 25 30 10Reversed array: 10 30 25 44 13 72 34Sorted array: 10 13 25 30 34 44 72
* * *
## Common Method Examples
**1. Array.Clear(Array, int index, int length)**
Sets a range of elements in the array to the default value of each element 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 a source array to a destination array.
int[] source = {1, 2, 3};int[] destination = new int;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 value 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 value 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 a sorted one-dimensional array for a value and returns its index.
int[] arr = {1, 2, 3, 4, 5};int index = Array.BinarySearch(arr, 3); // index = 2
**Note:** The array must be sorted before using BinarySearch.
**9. Array.Resize(ref T[] array, int newSize)**
Changes the number of elements of a one-dimensional array to the specified new size.
int[] arr = {1, 2, 3};Array.Resize(ref arr, 5); // arr = {1, 2, 3, 0, 0}
**10. Array.Exists(T[] array, Predicate match)**
Determines whether an array contains elements that match the conditions defined by the specified predicate.
int[] arr = {1, 2, 3};bool exists = Array.Exists(arr, x => x == 2); // exists = true
**11. Array.Find(T[] array, Predicate match)**
Searches for an element that matches the conditions defined by the specified predicate.
int[] arr = {1, 2, 3, 4};int result = Array.Find(arr, x => x > 2); // result = 3
**12. Array.FindAll(T[] array, Predicate match)**
Retrieves all the elements that match the conditions defined by the specified predicate.
int[] arr = {1, 2, 3, 4};int[] results = Array.FindAll(arr, x => x > 2); // results = {3, 4}
**13. Array.FindIndex(T[] array, Predicate match)**
Returns the index of the first occurrence of an element that matches the conditions defined by the specified predicate.
int[] arr = {1, 2, 3, 4};int index = Array.FindIndex(arr, x => x > 2); // index = 2
**14. Array.FindLast(T[] array, Predicate match)**
Searches for an element that matches the conditions defined by the specified predicate and returns the last occurrence.
int[] arr = {1, 2, 3, 4};int result = Array.FindLast(arr, x => x > 2); // result = 4
**15. Array.FindLastIndex(T[] array, Predicate match)**
Returns the index of the last occurrence of an element that matches the conditions defined by the specified predicate.
int[] arr = {1, 2, 3, 4};int index = Array.FindLastIndex(arr, x => x > 2); // index = 3
**16. Array.TrueForAll(T[] array, Predicate match)**
Determines whether every element in the array matches the conditions defined by the specified predicate.
int[] arr = {1, 2, 3};bool allPositive = Array.TrueForAll(arr, x => x > 0); // allPositive = true
**17. Array.ForEach(T[] array, Action action)**
Performs the specified action on each element of the specified array.
int[] arr = {1, 2, 3};Array.ForEach(arr, x => Console.WriteLine(x)); // Outputs 1 2 3
**18. Array.ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)**
Copies a range of elements from the source Array to the destination Array, guaranteeing that if the copy operation succeeds, all changes are committed.
int[] source = {1, 2, 3, 4, 5};int[] destination = new int;Array.ConstrainedCopy(source, 0, destination, 0, 5);
**19. Array.Fill(T[] array, T value)**
Sets all the elements of the array to the specified value.
int[] arr = new int;Array.Fill(arr, 10); // arr = {10, 10, 10, 10, 10}
**20. Array.AsReadOnly(T[] array)**
Returns a read-only wrapper for the specified array.
int[] arr = {1, 2, 3};var readOnlyArr = Array.AsReadOnly(arr);// readOnlyArr = 5; // Compile error, collection is read-only
## Example
using System;
class Program
{
static void Main()
{
// Create and initialize an array
int[] numbers ={5, 2, 8, 1, 3};
// Sort the array
Array.Sort(numbers);// numbers = {1, 2, 3, 5, 8}
// Search for an element
int index = Array.BinarySearch(numbers, 5);// index = 3
// Reverse the array
Array.Reverse(numbers);// numbers = {8, 5, 3, 2, 1}
// Check if any element is greater than 6
bool exists = Array.Exists(numbers, x => x >6);// exists = true
// Multiply each element 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);// Sets 2 elements starting at index 5 to 10
// numbers = {8, 5, 3, 2, 1, 10, 10}
}
}
[ C# Arrays](#)
YouTip