C# Reference ยท Collections
The Array class
Reference for System.Array static helpers in C#: Sort, Reverse, IndexOf, BinarySearch, Copy, Resize, Fill, Find and Exists, with return values and errors.
Every C# array, such as int[] or string[], derives from System.Array. The class provides the members that all arrays share (Length, Rank, GetLength, Clone, CopyTo) and a set of static helper methods for sorting, searching, copying and filling arrays.
Arrays have a fixed size. Methods like Array.Resize do not grow an array in place: they allocate a new one and copy the elements. If you need a collection that grows, use List<T>.
int[] numbers = [5, 2, 9, 1]; Array.Sort(numbers); // 1, 2, 5, 9 int index = Array.IndexOf(numbers, 5); // 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static void Sort<T>(T[] array); public static void Sort<T>(T[] array, Comparison<T> comparison); public static void Sort<T>(T[] array, IComparer<T>? comparer); public static void Reverse<T>(T[] array); public static int IndexOf<T>(T[] array, T value); public static int LastIndexOf<T>(T[] array, T value); public static int BinarySearch<T>(T[] array, T value); public static void Copy(Array source, Array destination, int length); public static void Copy(Array source, int sourceIndex, Array destination, int destinationIndex, int length); public static void Resize<T>(ref T[]? array, int newSize); public static void Fill<T>(T[] array, T value); public static void Clear(Array array, int index, int length); public static bool Exists<T>(T[] array, Predicate<T> match); public static T? Find<T>(T[] array, Predicate<T> match); public static T[] FindAll<T>(T[] array, Predicate<T> match); public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter); public static T[] Empty<T>();
| Name | Description |
|---|---|
array |
The array to read or change. Must not be null (except for Resize, which then creates a new array). |
comparison / comparer |
Defines the order. Without one, Comparer<T>.Default is used, which needs T to implement IComparable<T>. |
value |
The value to find or store. Equality uses EqualityComparer<T>.Default. |
length, index |
The number of elements and the starting position of the range. |
match |
A predicate that decides which elements qualify. |
Returns: IndexOf and LastIndexOf return -1 when the value is missing. BinarySearch returns the index if found, otherwise the bitwise complement (~) of the index where the value would be inserted, which is always negative. Find returns default(T) when nothing matches, so 0 or null.
Errors: ArgumentNullException for a null array; ArgumentException when Copy would write past the end of the destination; ArgumentOutOfRangeException for a bad index or length; InvalidOperationException from Sort when elements cannot be compared.
Usage notes
Sortis not stable. Equal elements may change their relative order. Use LINQOrderBywhen the order of equal items matters.BinarySearchrequires a sorted array. On unsorted data the result is meaningless. With duplicates it may return any matching index.Copyhandles overlapping ranges correctly when the source and destination are the same array.CloneandCopyare shallow. For arrays of reference types, the copy holds the same objects.Resizeis O(n). Calling it in a loop to add one item at a time is quadratic. UseList<T>.- Prefer spans for slices.
array.AsSpan(1, 3)views part of an array without copying, andarray[1..4]on an array does copy. Array.Empty<T>()returns a cached zero-length array, a good value to return instead of allocating a new empty array.- Covariance risk: a
string[]can be assigned to anobject[]variable, but storing anintthen throwsArrayTypeMismatchException. - Multi-dimensional arrays (
int[,]) reportLengthas the total element count; useGetLength(dimension)for each size.
Related
- List
, List .Sort() , Collections overview - Lessons: Arrays, Spans and memory