C# Array Class

C# Arrays

The Array class is the base class for all arrays in C#, defined in the System namespace. The Array class provides various properties and methods for arrays.

In C#, the Array class is the base class for all arrays, located under the System namespace.

An array is a collection used to store a fixed number of elements of the same type. Understanding the characteristics and methods of the Array class is very important for writing efficient C# programs.

The following is a detailed introduction to the C# Array class, including its characteristics, commonly used methods, properties, and usage examples.

Features

  • Type Safety: Arrays can only store elements of a specified type, and the type is determined at declaration time.
  • Fixed length: The length of an array cannot be changed after it is created.
  • Index access: Elements in an array are accessed by index, and the index starts from 0.
  • Multidimensional 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 in the Array class:

Attribute nameDescriptionExample codeOutput
LengthGets the total number of elements in the array.int[] arr = {1, 2, 3};
int length = arr.Length;
3
RankGets the rank of the array (i.e., the number of dimensions of the array).int[,] matrix = new int[2, 3];
int rank = matrix.Rank;
2
IsFixedSizeDetermines whether the size of the array is fixed.int[] arr = {1, 2, 3};
bool fixedSize = arr.IsFixedSize;
true
IsReadOnlyDetermines whether the array is read-only.int[] arr = {1, 2, 3};
bool readOnly = arr.IsReadOnly;
false
IsSynchronizedDetermines whether the array is thread-safe.int[] arr = {1, 2, 3};
bool sync = arr.IsSynchronized;
false
SyncRootGets the object used to synchronize array access, typically used in 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 the Microsoft C# documentation.

Methods of the Array class

The following table lists some of the most commonly used methods in the Array class:

Serial NumberMethods & Description
1Clear
Sets a range of elements in an array to zero, false, or null, depending on the element type.
2Copy(Array, Array, Int32)
Copies a range of elements from the array starting at the first element to the first element position of another array. The length is specified by a 32-bit integer.
3CopyTo(Array, Int32)
Copies all elements from the current one-dimensional array to a specified index position in a specified one-dimensional array. The index is specified by a 32-bit integer.
4GetLength
Gets a 32-bit integer that represents the total number of elements in the specified dimension of the array.
5GetLongLength
Gets a 64-bit integer that represents the total number of elements in the specified dimension of the array.
6GetLowerBound
Gets the lower bound of a specified dimension in the array.
7GetType
Gets the type of the current instance. Inherited from Object.
8GetUpperBound
Gets the upper bound of a specified dimension in the array.
9GetValue(Int32)
Gets the value at the specified position in a one-dimensional array. The index is specified by a 32-bit integer.
10IndexOf(Array, Object)
Searches for the specified object and returns the index of its first occurrence in the entire one-dimensional array.
11Reverse(Array)
Reverses the order of elements in the entire one-dimensional array.
12SetValue(Object, Int32)
Sets the value of the element at the specified position in a one-dimensional array. The index is specified by a 32-bit integer.
13Sort(Array)
Sorts the elements in the entire one-dimensional array using the IComparable implementation of each element of the array.
14ToString
Returns a string that represents the current object. Inherited from Object.

More method reference notes

  1. AsReadOnly<T>(T[])

    • Returns a read-only wrapper for the specified array.
  2. BinarySearch

    • BinarySearch(Array, Int32, Int32, Object, IComparer): Searches for a value in a sorted array, using the specifiedIComparerInterface.
    • BinarySearch(Array, Int32, Int32, Object): Searches for a value in a sorted array, usingIComparableInterface.
    • BinarySearch(Array, Object, IComparer): Searches a sorted array, using the specifiedIComparerInterface.
    • BinarySearch(Array, Object): Searches a sorted array, usingIComparableInterface.
    • BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>): Searches for a value in a generic array range, using the specifiedIComparer<T>Interface.
    • BinarySearch<T>(T[], Int32, Int32, T): Searches for a value within a generic array range, usingIComparable<T>Interface.
    • BinarySearch<T>(T[], T, IComparer<T>): Searches a sorted generic array, using the specifiedIComparer<T>Interface.
    • BinarySearch<T>(T[], T): Searches a sorted generic array, usingIComparable<T>Interface.
  3. Clear

    • Clear(Array, Int32, Int32): Sets the elements in the specified range of an array to their default values.
    • Clear(Array): Clears the contents of the array.
  4. Clone

    • Creates a shallow copy of the array.
  5. ConstrainedCopy

    • Copies a specified range of elements from the source array to the destination array, ensuring that changes are made only after the entire copy operation succeeds.
  6. ConvertAll<TInput, TOutput>(TInput[], Converter<TInput, TOutput>)

    • Converts an array of one type to an array of another type.
  7. Copy

    • Copy(Array, Array, Int32): Copies the array elements to the destination array, with the length specified by a 32-bit integer.
    • Copy(Array, Array, Int64): Copies the array elements to the destination array, with the length specified by 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.
  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 using the specified dimensions.
    • CreateInstance(Type, Int64[]): Creates a multi-dimensional array using 64-bit integer dimensions.
  9. Empty<T>

    • Returns an empty array instance.
  10. Exists<T>(T[], Predicate<T>)

    • Determines whether an array contains elements that meet the specified condition.
  11. Fill<T>(T[], T, Int32, Int32)

    • Fills all elements in an array within the specified index range with a given value.
    • Fill<T>(T[], T): Fills all elements of the entire array with a given value.
  12. Find

    • Find<T>(T[], Predicate<T>): Searches for the first element that matches the conditions and returns it.
    • FindAll<T>(T[], Predicate<T>): Returns all elements that match the conditions.
    • FindIndex<T>(T[], Int32, Int32, Predicate<T>): Within the specified range of an array, returns the index of the first element that meets the condition.
    • FindIndex<T>(T[], Int32, Predicate<T>): After the specified index, returns the index of the first element that meets the condition.
    • FindIndex<T>(T[], Predicate<T>): Returns the index of the first element that meets the condition.
    • FindLast<T>(T[], Predicate<T>): Returns the last element that meets the condition.
    • FindLastIndex<T>(T[], Int32, Int32, Predicate<T>): Within the specified range of an array, returns the index of the last element that meets the condition.
    • FindLastIndex<T>(T[], Predicate<T>): Returns the index of the last element that meets the condition.
  13. ForEach<T>(T[], Action<T>)

    • Performs the specified operation on each element of the array.
  14. GetEnumerator()

    • Gets the enumerator of the array.
  15. GetLength

    • GetLength(Int32): Gets the number of elements in the specified dimension of an array.
  16. GetLongLength(Int32)

    • Gets the length of the array as a 64-bit integer.
  17. GetLowerBound(Int32)

    • Gets the index of the first element in the specified dimension of an array.
  18. GetUpperBound(Int32)

    • Gets the index of the last element in the specified dimension of an array.
  19. GetValue

    • GetValue(Int32): Gets the value at the specified index of a one-dimensional array.
    • GetValue(Int32, Int32): Gets the value at the specified index of a two-dimensional array.
    • GetValue(Int32, Int32, Int32): Gets the value at the specified index of a three-dimensional array.
    • GetValue(Int32[]): Gets the value of a multi-dimensional array.
  20. 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 in the array.
    • IndexOf(Array, Object, Int32, Int32): Returns the index of the first occurrence of the specified object within the specified range in the array.
  21. LastIndexOf

    • similar toIndexOf, but searches from the end of the array.
  22. Resize<T>(T[], Int32)

    • Changes the size of a one-dimensional array.
  23. Reverse

    • Reverse(Array): Reverses the order of elements in the array.
    • Reverse<T>(T[]): Reverses the order of elements in a generic array.
  24. 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 of a two-dimensional array.
  25. Sort

    • Sort(Array): Sorts the array.
    • Sort<T>(T[], IComparer<T>): Sorts a generic array.
  26. TrueForAll<T>(T[], Predicate<T>)

    • Determines whether all elements in an array meet the condition.

For the complete list of methods of the Array class, please refer to the Microsoft C# documentation.

Example

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 array
            Array.Reverse(list);
            Console.Write("Reversed array: ");
            foreach (int i in list)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
           
            // Sort 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 results:

原始数组: 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 a specified range of elements in an 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 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 already be sorted.

9. Array.Resize(ref T[] array, int newSize)

Resizes a one-dimensional array.

int[] arr = {1, 2, 3};
Array.Resize(ref arr, 5); // arr = {1, 2, 3, 0, 0}

10. Array.Exists<T>(T[] array, Predicate match)

Determines whether there is an element in the array that meets the condition.

int[] arr = {1, 2, 3};
bool exists = Array.Exists(arr, x => x == 2); // exists = true

11. Array.Find<T>(T[] array, Predicate match)

Finds the first element in the array that meets the condition.

int[] arr = {1, 2, 3, 4};
int result = Array.Find(arr, x => x > 2); // result = 3

12. Array.FindAll<T>(T[] array, Predicate match)

Finds all elements in the array that meet the condition.

int[] arr = {1, 2, 3, 4};
int[] results = Array.FindAll(arr, x => x > 2); // results = {3, 4}

13. Array.FindIndex<T>(T[] array, Predicate match)

Returns the index of the first element that meets the condition.

int[] arr = {1, 2, 3, 4};
int index = Array.FindIndex(arr, x => x > 2); // index = 2

14. Array.FindLast<T>(T[] array, Predicate match)

Finds the last element that matches the conditions.

int[] arr = {1, 2, 3, 4};
int result = Array.FindLast(arr, x => x > 2); // result = 4

15. Array.FindLastIndex<T>(T[] array, Predicate match)

Returns the index of the last element that meets the condition.

int[] arr = {1, 2, 3, 4};
int index = Array.FindLastIndex(arr, x => x > 2); // index = 3

16. Array.TrueForAll<T>(T[] array, Predicate match)

Determines whether all elements in the array satisfy the condition.

int[] arr = {1, 2, 3};
bool allPositive = Array.TrueForAll(arr, x => x > 0); // allPositive = true

17. Array.ForEach<T>(T[] array, Action action)

Performs the specified operation 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 a portion of an array to another array, 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<T>(T[] array, T value)

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<T>(T[] array)

Returns a read-only wrapper for the array.

int[] arr = {1, 2, 3};
var readOnlyArr = Array.AsReadOnly(arr);
// readOnlyArr[0] = 5; // 编译错误,集合是只读的

Example

using System;

class Program
{
    static void Main()
    {
        // Create and initialize an array
        int[] numbers = {5, 2, 8, 1, 3};

        // Sort array
        Array.Sort(numbers); // numbers = {1, 2, 3, 5, 8}

        // Find element
        int index = Array.BinarySearch(numbers, 5); // index = 3

        // Reverse array
        Array.Reverse(numbers); // numbers = {8, 5, 3, 2, 1}

        // Check if there are any elements greater than 6
        bool exists = Array.Exists(numbers, x => x > 6); // exists = true

        // Multiply 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 new elements
        Array.Fill(numbers, 10, 5, 2); // Set the 2 elements starting at index 5 to 10
        // numbers = {8, 5, 3, 2, 1, 10, 10}
    }
}

C# Arrays

other extensions