C# array
last modified November 15, 2026
In this article, we explore arrays in C#, a fundamental data structure used for
storing multiple elements efficiently. We create and initialize arrays, access,
modify, and traverse their elements, work with multidimensional and jagged
arrays, and use the methods of the Array class and LINQ.
Understanding arrays
An array is a collection of data that stores multiple values under a single variable name. Unlike scalar variables, which hold only one value at a time, arrays enable working with many related values. Each value in an array is called an element.
Arrays store elements of the same data type. Each element is accessed
using an index, which identifies its position within the
array. Indexing in C# is zero-based: the first element is at index
0, the second at index 1, and the last at index
Length - 1.
Arrays are reference types. An array variable holds a
reference to the array object; the elements themselves are stored in one
contiguous block of memory. Assigning an array to another variable or passing
it to a method copies the reference, not the elements. All arrays derive from
the System.Array class, which provides methods for sorting,
searching, copying, and resizing.
The length of an array is fixed when the array is created. When we need a
collection that grows and shrinks, we use List<T> or another
collection type. Arrays remain the simplest and fastest choice for a fixed
number of elements, and many collections use arrays internally.
Declaring and initializing arrays
An array type is written as the element type followed by square brackets, for
example int[] or string[]. The array object is
created with the new operator, which takes the number of
elements.
int[] vals = new int[5];
vals[0] = 1;
vals[1] = 2;
vals[2] = 3;
vals[3] = 4;
vals[4] = 5;
for (int i = 0; i < vals.Length; i++)
{
Console.WriteLine(vals[i]);
}
We create an array of five integers, assign the values one by one, and print them.
int[] vals = new int[5];
The declaration creates an array which can hold five integers.
vals[0] = 1; vals[1] = 2;
We assign values to the elements. The index is placed in the square brackets;
vals[0] is the first element of the array.
for (int i = 0; i < vals.Length; i++)
{
Console.WriteLine(vals[i]);
}
The Length property gives the number of elements in the array.
Since arrays are zero-based, the valid indexes are 0 to
Length - 1.
$ dotnet run 1 2 3 4 5
Array initializers
An array can be declared and filled in one statement with an array initializer. The values are placed in curly brackets and the compiler counts them for us.
int[] a = new int[] { 2, 4, 5, 6, 7, 3, 2 };
int[] b = { 2, 4, 5, 6, 7, 3, 2 };
Console.WriteLine(string.Join(" ", a));
Console.WriteLine(string.Join(" ", b));
The program creates two arrays with the same content.
int[] a = new int[] { 2, 4, 5, 6, 7, 3, 2 };
The length of the array is not specified; it is determined by the number of values in the initializer.
int[] b = { 2, 4, 5, 6, 7, 3, 2 };
In a declaration, the new int[] part can be omitted. The compiler
translates this line into the same code as the previous one.
$ dotnet run 2 4 5 6 7 3 2 2 4 5 6 7 3 2
Collection expressions
Since C# 12, we can initialize arrays with collection expressions. The values are placed in square brackets. The same syntax works for lists, spans, and other collection types.
int[] vals = [1, 2, 3, 4, 5];
int[] more = [0, .. vals, 6, 7];
string[] empty = [];
Console.WriteLine(string.Join(" ", vals));
Console.WriteLine(string.Join(" ", more));
Console.WriteLine($"empty has {empty.Length} elements");
In the program, we create arrays with collection expressions.
int[] vals = [1, 2, 3, 4, 5];
This syntax is short and common in many programming languages.
int[] more = [0, .. vals, 6, 7];
The spread element .. inserts all elements of another collection.
string[] empty = [];
An empty collection expression creates an empty array.
$ dotnet run 1 2 3 4 5 0 1 2 3 4 5 6 7 empty has 0 elements
Default values
When an array is created with new and a length, its elements get
the default value of the element type: zero for numbers, false
for booleans, and null for reference types.
int[] nums = new int[3];
double[] weights = new double[3];
bool[] flags = new bool[3];
string?[] names = new string?[3];
Console.WriteLine(string.Join(", ", nums));
Console.WriteLine(string.Join(", ", weights));
Console.WriteLine(string.Join(", ", flags));
Console.WriteLine(names[0] is null);
We create four arrays without initializers and print their content.
string?[] names = new string?[3];
The elements of a string array are null. We use the nullable
string? type to make this explicit.
$ dotnet run 0, 0, 0 0, 0, 0 False, False, False True
C# Array.Fill
The Array.Fill method assigns the given value to all elements of
an array, or to a range of elements.
int[] vals = new int[10];
Array.Fill(vals, -1);
Console.WriteLine(string.Join(", ", vals));
Array.Fill(vals, 7, 2, 5);
Console.WriteLine(string.Join(", ", vals));
char[] line = new char[20];
Array.Fill(line, '-');
Console.WriteLine(line);
We fill an integer array and a character array.
Array.Fill(vals, -1);
All ten elements are set to -1.
Array.Fill(vals, 7, 2, 5);
This overload takes a start index and a count. Five elements, starting at index 2, are set to 7.
char[] line = new char[20]; Array.Fill(line, '-'); Console.WriteLine(line);
A character array filled with dashes gives a simple separator line. The
WriteLine method has an overload which prints a character array
as text.
$ dotnet run -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -1, -1, 7, 7, 7, 7, 7, -1, -1, -1 --------------------
C# array accessing elements
After an array is created, its elements can be accessed by their index. The
index from end operator ^ counts from the end of the array:
^1 is the last element and ^n is the element at
index Length - n.
string[] names = ["Jane", "Thomas", "Lucy", "David"];
Console.WriteLine(names[0]);
Console.WriteLine(names[1]);
Console.WriteLine(names[2]);
Console.WriteLine(names[3]);
Console.WriteLine("*************************");
Console.WriteLine(names[^1]);
Console.WriteLine(names[^2]);
Console.WriteLine(names[^3]);
Console.WriteLine(names[^4]);
Console.WriteLine("*************************");
try
{
Console.WriteLine(names[4]);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
In the example, we create an array of names and access its elements from the start and from the end.
Console.WriteLine(names[0]); Console.WriteLine(names[1]);
With the names[0] construct, we refer to the first element of the
array.
Console.WriteLine(names[^1]); Console.WriteLine(names[^2]);
We access the elements from the end.
try
{
Console.WriteLine(names[4]);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
The array has four elements, so index 4 is out of range. Every array access is
checked at runtime and an invalid index throws an
IndexOutOfRangeException.
$ dotnet run Jane Thomas Lucy David ************************* David Lucy Thomas Jane ************************* Index was outside the bounds of the array.
C# implicitly-typed array
With var and new[], the compiler infers the element
type from the values in the initializer.
var vals = new[] { 1, 2, 3, 4, 5 };
var words = new[] { "cup", "falcon", "word", "water" };
var mixed = new[] { 1, 2.5, 3 };
Console.WriteLine(vals.GetType());
Console.WriteLine(words.GetType());
Console.WriteLine(mixed.GetType());
We create three implicitly-typed arrays.
var vals = new[] { 1, 2, 3, 4, 5 };
An array of integers is created. The compiler infers the type from the values.
We cannot use a collection expression with var, because a
collection expression has no type of its own; it needs a target type.
var mixed = new[] { 1, 2.5, 3 };
When the values have different types, the compiler picks the best common type.
The integers are converted to double.
$ dotnet run System.Int32[] System.String[] System.Double[]
C# array modify elements
Array elements are not read-only; we can assign new values to them at any time.
int[] vals = [1, 2, 3, 4];
vals[0] *= 2;
vals[1] *= 2;
vals[2] *= 2;
vals[3] *= 2;
Console.WriteLine($"[{string.Join(", ", vals)}]");
We have an array of four integers. Each of the values is multiplied by two.
vals[0] *= 2;
The compound assignment reads the element, multiplies it, and stores the new value in the same position.
Console.WriteLine($"[{string.Join(", ", vals)}]");
The string.Join method creates one string from all elements of
the array. The elements are separated with a comma and a space.
$ dotnet run [2, 4, 6, 8]
C# array slices
The range operator .. creates array slices. The start of the
range is inclusive and the end is exclusive. A slice of an array is a new
array; when we want a view of the original elements, we use a span.
int[] vals = [1, 2, 3, 4, 5, 6, 7];
int[] vals2 = vals[1..5];
Console.WriteLine($"[{string.Join(", ", vals2)}]");
int[] vals3 = vals[..6];
Console.WriteLine($"[{string.Join(", ", vals3)}]");
int[] vals4 = vals[3..];
Console.WriteLine($"[{string.Join(", ", vals4)}]");
int[] vals5 = vals[^3..];
Console.WriteLine($"[{string.Join(", ", vals5)}]");
vals2[0] = 100;
Console.WriteLine($"[{string.Join(", ", vals)}]");
Span<int> view = vals.AsSpan(1..5);
view[0] = 100;
Console.WriteLine($"[{string.Join(", ", vals)}]");
The example works with array ranges.
int[] vals2 = vals[1..5];
We create a slice containing the elements from index 1 to index 4.
int[] vals3 = vals[..6];
If the start index is omitted, the slice starts at index 0.
int[] vals4 = vals[3..];
If the end index is omitted, the slice goes until the end of the array.
int[] vals5 = vals[^3..];
Ranges can use the index from end operator; this slice holds the last three elements.
vals2[0] = 100;
Changing an element of the slice does not change the original array; the slice is a copy.
Span<int> view = vals.AsSpan(1..5); view[0] = 100;
A Span<int> refers to the elements of the original array
without copying them. Writing through the span modifies the array.
$ dotnet run [2, 3, 4, 5] [1, 2, 3, 4, 5, 6] [4, 5, 6, 7] [5, 6, 7] [1, 2, 3, 4, 5, 6, 7] [1, 100, 3, 4, 5, 6, 7]
C# traversing arrays
We often need to go through all elements of an array. The for
loop gives us the index, the foreach loop gives us the elements.
string[] planets = [ "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" ];
for (int i = 0; i < planets.Length; i++)
{
Console.Write($"{planets[i]} ");
}
Console.WriteLine();
foreach (string planet in planets)
{
Console.Write($"{planet} ");
}
Console.WriteLine();
foreach (var (idx, planet) in planets.Index())
{
Console.WriteLine($"{idx + 1}. {planet}");
}
An array of planet names is created. We print the values with three different loops.
for (int i = 0; i < planets.Length; i++)
{
Console.Write($"{planets[i]} ");
}
The for loop uses the Length property as its upper
bound.
foreach (string planet in planets)
{
Console.Write($"{planet} ");
}
The foreach statement is more compact. In each cycle, the
planet variable gets the next value from the array.
foreach (var (idx, planet) in planets.Index())
{
Console.WriteLine($"{idx + 1}. {planet}");
}
The LINQ Index method, available since .NET 9, pairs each element
with its index. We get both values in a foreach loop.
$ dotnet run Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 1. Mercury 2. Venus 3. Earth 4. Mars 5. Jupiter 6. Saturn 7. Uranus 8. Neptune
C# pass array as function argument
When an array is passed to a method, the reference to the array is copied. The method works with the same array object, so it can change the elements of the caller's array. Assigning a new array to the parameter, however, does not affect the caller.
int[] vals = [1, 2, 3, 4, 5];
ModifyArray(vals);
Console.WriteLine(string.Join(", ", vals));
ReplaceArray(vals);
Console.WriteLine(string.Join(", ", vals));
void ModifyArray(int[] data)
{
Array.Reverse(data);
}
void ReplaceArray(int[] data)
{
data = [10, 20, 30];
}
We pass an array of integers to two local functions.
void ModifyArray(int[] data)
{
Array.Reverse(data);
}
The ModifyArray function reverses the elements in place. Since
the parameter refers to the same array as vals, the change is
visible after the call.
void ReplaceArray(int[] data)
{
data = [10, 20, 30];
}
The ReplaceArray function makes its parameter point to a new
array. The vals variable still refers to the original array,
which is unchanged. To replace the caller's array, the parameter would have to
be declared with the ref keyword.
$ dotnet run 5, 4, 3, 2, 1 5, 4, 3, 2, 1
C# array dimensions
So far, we have worked with one-dimensional arrays. The number of indexes needed to specify an element is called the dimension, or rank, of the array. C# has true multidimensional arrays, also called rectangular arrays, whose dimensions are separated by commas in the brackets.
Two-dimensional array
A two-dimensional array is declared with one comma in the brackets:
int[,]. It can be seen as a table of rows and columns.
int[,] twodim = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
int d1 = twodim.GetLength(0);
int d2 = twodim.GetLength(1);
Console.WriteLine($"{d1} rows, {d2} columns, {twodim.Length} elements");
for (int i = 0; i < d1; i++)
{
for (int j = 0; j < d2; j++)
{
Console.Write($"{twodim[i, j]} ");
}
Console.WriteLine();
}
We create a two-dimensional array with two rows and three columns and print it as a table.
int[,] twodim = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
Each inner pair of curly brackets holds one row.
int d1 = twodim.GetLength(0); int d2 = twodim.GetLength(1);
The GetLength method returns the number of elements in the given
dimension. The Length property of a multidimensional array is the
total number of elements.
Console.Write($"{twodim[i, j]} ");
An element of a two-dimensional array is accessed with two indexes separated by a comma.
$ dotnet run 2 rows, 3 columns, 6 elements 1 2 3 4 5 6
Traversing with foreach
The foreach loop goes over all elements of a multidimensional
array in row-major order: all elements of the first row, then the second row,
and so on.
int[,] vals = new int[4, 2]
{
{ 9, 99 },
{ 3, 33 },
{ 4, 44 },
{ 1, 11 }
};
foreach (var val in vals)
{
Console.Write($"{val} ");
}
Console.WriteLine();
The array has four rows and two columns. The foreach loop returns
the eight values one by one.
int[,] vals = new int[4, 2]
When we specify the dimensions together with an initializer, the number of values must match them exactly; otherwise, the code does not compile.
$ dotnet run 9 99 3 33 4 44 1 11
Three-dimensional array
A three-dimensional array has two commas in the brackets and needs three indexes to access an element.
int[,,] n3 =
{
{ { 12, 2, 8 }, { 14, 5, 2 } },
{ { 3, 26, 9 }, { 4, 11, 2 } }
};
int d1 = n3.GetLength(0);
int d2 = n3.GetLength(1);
int d3 = n3.GetLength(2);
Console.WriteLine($"Dimensions: {d1} x {d2} x {d3}");
for (int i = 0; i < d1; i++)
{
for (int j = 0; j < d2; j++)
{
for (int k = 0; k < d3; k++)
{
Console.Write($"{n3[i, j, k]} ");
}
Console.Write("| ");
}
Console.WriteLine();
}
We create a 2 x 2 x 3 array and print its elements with three nested loops.
int[,,] n3 =
{
{ { 12, 2, 8 }, { 14, 5, 2 } },
{ { 3, 26, 9 }, { 4, 11, 2 } }
};
The initializer has three levels of curly brackets, one for each dimension.
Console.Write($"{n3[i, j, k]} ");
We use three indexes to retrieve a value from the array.
$ dotnet run Dimensions: 2 x 2 x 3 12 2 8 | 14 5 2 | 3 26 9 | 4 11 2 |
C# Rank
The Rank property gives the number of dimensions of an array.
int[] a1 = [1, 2];
int[,] a2 = { { 1 }, { 2 } };
int[,,] a3 = { { { 1, 2 }, { 2, 1 } } };
int[][] a4 = [[1, 2], [3]];
Console.WriteLine(a1.Rank);
Console.WriteLine(a2.Rank);
Console.WriteLine(a3.Rank);
Console.WriteLine(a4.Rank);
We have four arrays and print the rank of each of them.
int[][] a4 = [[1, 2], [3]];
The last array is a jagged array, which is covered in the next section. It is a one-dimensional array whose elements happen to be arrays, so its rank is 1.
$ dotnet run 1 2 3 1
C# jagged arrays
Rectangular arrays have rows of the same length. A jagged array is an
array of arrays; each inner array can have a different length. It is declared
with two pairs of square brackets: int[][].
int[][] jagged =
[
[1, 2],
[1, 2, 3],
[1, 2, 3, 4]
];
foreach (int[] row in jagged)
{
Console.WriteLine($"{row.Length}: {string.Join(" ", row)}");
}
Console.WriteLine(jagged[2][3]);
jagged[0] = new int[5];
Console.WriteLine(string.Join(" ", jagged[0]));
This is an example of a jagged array.
int[][] jagged =
[
[1, 2],
[1, 2, 3],
[1, 2, 3, 4]
];
We create an array of three integer arrays with collection expressions. The inner arrays have two, three, and four elements.
foreach (int[] row in jagged)
{
Console.WriteLine($"{row.Length}: {string.Join(" ", row)}");
}
Each element of the outer array is an int[] with its own
Length.
Console.WriteLine(jagged[2][3]);
An element is accessed with two pairs of brackets: the first selects the inner array, the second the element in it.
jagged[0] = new int[5];
Since the rows are independent arrays, we can replace a row with an array of a different length.
$ dotnet run 2: 1 2 3: 1 2 3 4: 1 2 3 4 4 0 0 0 0 0
C# array sort & reverse
The Array.Sort method sorts the elements of an array in place.
The Array.Reverse method reverses the order of the elements.
string[] names = ["Jane", "Frank", "Alexandra", "Tom", "Bo"];
Array.Sort(names);
Console.WriteLine(string.Join(" ", names));
Array.Reverse(names);
Console.WriteLine(string.Join(" ", names));
Array.Sort(names, (a, b) => a.Length.CompareTo(b.Length));
Console.WriteLine(string.Join(" ", names));
In this example, we sort and reverse an array of strings.
Array.Sort(names);
The static Sort method sorts the strings alphabetically, using
the comparison rules of the current culture.
Array.Reverse(names);
The Reverse method reverses the sequence of the elements in the
array.
Array.Sort(names, (a, b) => a.Length.CompareTo(b.Length));
An overload of Sort takes a Comparison<T>
delegate. Here we sort the names by their length. Note that
Array.Sort is not stable: elements which compare as equal may
change their relative order.
$ dotnet run Alexandra Bo Frank Jane Tom Tom Jane Frank Bo Alexandra Bo Tom Jane Frank Alexandra
Sorting with LINQ
Alternatively, we can sort arrays with the LINQ Order,
OrderDescending, OrderBy, and ThenBy
methods. Unlike Array.Sort, they do not change the array; they
return a new sorted sequence. LINQ sorting is stable.
string[] names = ["Jane", "Frank", "Alice", "Tom"];
var sorted = names.Order();
Console.WriteLine(string.Join(" ", sorted));
var sorted2 = names.OrderDescending();
Console.WriteLine(string.Join(" ", sorted2));
var byLength = names.OrderBy(name => name.Length).ThenBy(name => name);
Console.WriteLine(string.Join(" ", byLength));
Console.WriteLine(string.Join(" ", names));
The program sorts an array of strings in ascending and descending order, and by length.
var byLength = names.OrderBy(name => name.Length).ThenBy(name => name);
The names are sorted by length; names of the same length are sorted alphabetically.
Console.WriteLine(string.Join(" ", names));
The last line shows that the original array is untouched.
$ dotnet run Alice Frank Jane Tom Tom Jane Frank Alice Tom Jane Alice Frank Jane Frank Alice Tom
C# array GetValue & SetValue
The SetValue method sets the element at the specified position
and the GetValue method returns it. These methods are defined on
the Array base class. They are useful when we work with an
Array reference whose element type or rank is not known at
compile time; for ordinary arrays, the indexer is simpler and faster.
string[] names = ["Jane", "Frank", "Alice", "Tom"];
names.SetValue("Beky", 1);
names.SetValue("Erzebeth", 3);
Console.WriteLine(names.GetValue(1));
Console.WriteLine(names.GetValue(3));
int[,] grid = { { 1, 2 }, { 3, 4 } };
Array arr = grid;
arr.SetValue(40, 1, 1);
Console.WriteLine(arr.GetValue(1, 1));
Console.WriteLine(grid[1, 1]);
This example uses the SetValue and GetValue methods.
names.SetValue("Beky", 1);
names.SetValue("Erzebeth", 3);
The SetValue method sets a value at a specific index in the
array.
Array arr = grid; arr.SetValue(40, 1, 1); Console.WriteLine(arr.GetValue(1, 1));
Through an Array reference, we cannot use the indexer. The
SetValue and GetValue methods take one index per
dimension. The change is visible through the grid variable,
which refers to the same array.
$ dotnet run Beky Erzebeth 40 40
C# array searching
The Array class provides several methods for searching elements
in an array, such as IndexOf, Exists,
Find, FindIndex, and FindAll.
string[] fruits = ["apple", "banana", "cherry", "date", "elderberry", "fig"];
int bananaIndex = Array.IndexOf(fruits, "banana");
Console.WriteLine($"Index of 'banana': {bananaIndex}");
int grapeIndex = Array.IndexOf(fruits, "grape");
Console.WriteLine($"Index of 'grape': {grapeIndex}");
Console.WriteLine($"Contains 'date'? {fruits.Contains("date")}");
bool hasShortName = Array.Exists(fruits, fruit => fruit.Length < 5);
Console.WriteLine($"Any fruit with name shorter than 5 chars? {hasShortName}");
string? startsWithC = Array.Find(fruits, fruit => fruit.StartsWith('c'));
Console.WriteLine($"First fruit starting with 'c': {startsWithC}");
int longIndex = Array.FindIndex(fruits, fruit => fruit.Length > 6);
Console.WriteLine($"Index of first name longer than 6 chars: {longIndex}");
string[] withE = Array.FindAll(fruits, fruit => fruit.Contains('e'));
Console.WriteLine($"Fruits containing 'e': {string.Join(", ", withE)}");
This example searches an array of fruit names.
int bananaIndex = Array.IndexOf(fruits, "banana");
Array.IndexOf returns the zero-based index of the first
occurrence of the value. If the value is not found, it returns -1.
Console.WriteLine($"Contains 'date'? {fruits.Contains("date")}");
The Contains method checks whether the array holds the value.
bool hasShortName = Array.Exists(fruits, fruit => fruit.Length < 5);
Array.Exists checks if any element satisfies the given predicate;
here, if any fruit name is shorter than five characters.
string? startsWithC = Array.Find(fruits, fruit => fruit.StartsWith('c'));
Array.Find returns the first element which matches the
predicate. If no element matches, it returns the default value of the type,
null for strings; hence the nullable string? type.
int longIndex = Array.FindIndex(fruits, fruit => fruit.Length > 6);
Array.FindIndex returns the index of the first matching element,
or -1.
string[] withE = Array.FindAll(fruits, fruit => fruit.Contains('e'));
Array.FindAll returns a new array with all matching elements.
$ dotnet run Index of 'banana': 1 Index of 'grape': -1 Contains 'date'? True Any fruit with name shorter than 5 chars? True First fruit starting with 'c': cherry Index of first name longer than 6 chars: 4 Fruits containing 'e': apple, cherry, date, elderberry
C# Array.BinarySearch
The methods in the previous section check the elements one by one. If the
array is sorted, Array.BinarySearch finds a value much faster: it
halves the searched range in each step.
int[] vals = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91];
int idx = Array.BinarySearch(vals, 23);
Console.WriteLine($"23 found at index {idx}");
int missing = Array.BinarySearch(vals, 20);
Console.WriteLine($"BinarySearch for 20 returned {missing}");
Console.WriteLine($"20 would be inserted at index {~missing}");
We search a sorted array of integers.
int idx = Array.BinarySearch(vals, 23);
When the value is found, the method returns its index.
int missing = Array.BinarySearch(vals, 20);
When the value is not found, the method returns a negative number. Its
bitwise complement, computed with the ~ operator, is the index
at which the value would have to be inserted to keep the array sorted.
$ dotnet run 23 found at index 5 BinarySearch for 20 returned -6 20 would be inserted at index 5
C# array resizing
Arrays in C# have a fixed size once created. The Array.Resize
method creates a new array of the given size, copies the elements to it, and
assigns the new array to the variable.
int[] numbers = [10, 20, 30];
int[] original = numbers;
Console.WriteLine($"Original array: [{string.Join(", ", numbers)}], Size: {numbers.Length}");
Array.Resize(ref numbers, 5);
numbers[3] = 40;
numbers[4] = 50;
Console.WriteLine($"Resized (larger) array: [{string.Join(", ", numbers)}], Size: {numbers.Length}");
Array.Resize(ref numbers, 2);
Console.WriteLine($"Resized (smaller) array: [{string.Join(", ", numbers)}], Size: {numbers.Length}");
Console.WriteLine($"Old array: [{string.Join(", ", original)}]");
The example uses Array.Resize to enlarge and shrink an array.
Array.Resize(ref numbers, 5);
The array is resized to five elements. The existing elements are copied, and
the new elements get the default value of the type, 0 for integers. The
ref keyword is needed because the method assigns a new array to
the variable.
Array.Resize(ref numbers, 2);
When the new size is smaller, only the first two elements are copied.
Console.WriteLine($"Old array: [{string.Join(", ", original)}]");
The original variable still refers to the first array, which has
not been changed. This shows that resizing does not modify an array; it
replaces it.
$ dotnet run Original array: [10, 20, 30], Size: 3 Resized (larger) array: [10, 20, 30, 40, 50], Size: 5 Resized (smaller) array: [10, 20], Size: 2 Old array: [10, 20, 30]
C# arrays of records
Arrays can store elements of any type, including user-defined records. Records
give us concise immutable data types with value-based equality and a readable
ToString output.
Person[] people =
[
new("Alice", 30),
new("Bob", 24),
new("Charlie", 35)
];
foreach (Person person in people)
{
Console.WriteLine(person);
}
Person oldest = people.MaxBy(p => p.Age)!;
Console.WriteLine($"Oldest: {oldest.Name}");
double avg = people.Average(p => p.Age);
Console.WriteLine($"Average age: {avg:F2}");
Person[] copy = [.. people];
Console.WriteLine(people[0] == copy[0]);
Console.WriteLine(ReferenceEquals(people, copy));
record Person(string Name, int Age);
This example defines a Person record and creates an array of
people.
Person[] people =
[
new("Alice", 30),
new("Bob", 24),
new("Charlie", 35)
];
The array is created with a collection expression. The target-typed
new expressions create the records.
Person oldest = people.MaxBy(p => p.Age)!;
The LINQ MaxBy method returns the element with the largest key.
It returns null for an empty array; we know ours is not empty, so
we use the null-forgiving operator.
Person[] copy = [.. people]; Console.WriteLine(people[0] == copy[0]); Console.WriteLine(ReferenceEquals(people, copy));
The spread element creates a new array with the same records. The records are equal, but the arrays are two distinct objects.
$ dotnet run
Person { Name = Alice, Age = 30 }
Person { Name = Bob, Age = 24 }
Person { Name = Charlie, Age = 35 }
Oldest: Charlie
Average age: 29.67
True
False
C# converting arrays and using LINQ
Arrays can be easily converted to other collection types like
List<T>. Language Integrated Query (LINQ) provides powerful
capabilities for querying and transforming arrays.
int[] numbers = [5, 1, 8, 2, 9, 4, 7, 3, 6];
List<int> numberList = numbers.ToList();
numberList.Add(10);
Console.WriteLine($"List: [{string.Join(", ", numberList)}]");
int[] back = numberList.ToArray();
Console.WriteLine($"Back to array, Length: {back.Length}");
var evenNumbers = numbers.Where(n => n % 2 == 0);
Console.WriteLine($"Even numbers: [{string.Join(", ", evenNumbers)}]");
var squaredNumbers = numbers.Select(n => n * n);
Console.WriteLine($"Squared numbers: [{string.Join(", ", squaredNumbers)}]");
var filteredAndSorted = numbers.Where(n => n > 5).Order();
Console.WriteLine($"Numbers > 5, sorted: [{string.Join(", ", filteredAndSorted)}]");
Console.WriteLine($"Sum: {numbers.Sum()}, Min: {numbers.Min()}, Max: {numbers.Max()}");
Console.WriteLine($"Any element > 8? {numbers.Any(n => n > 8)}");
This example converts an array to a list and back, and uses several LINQ methods.
List<int> numberList = numbers.ToList(); numberList.Add(10);
The ToList method copies the array into a new
List<int>. Unlike the array, the list can grow.
int[] back = numberList.ToArray();
The ToArray method converts the list back to an array.
var evenNumbers = numbers.Where(n => n % 2 == 0);
The Where method filters the array with a predicate; here it
selects the even numbers.
var squaredNumbers = numbers.Select(n => n * n);
The Select method projects each element into a new form; here it
squares each number.
var filteredAndSorted = numbers.Where(n => n > 5).Order();
LINQ methods can be chained. This line filters the numbers greater than five and sorts the result.
$ dotnet run List: [5, 1, 8, 2, 9, 4, 7, 3, 6, 10] Back to array, Length: 10 Even numbers: [8, 2, 4, 6] Squared numbers: [25, 1, 64, 4, 81, 16, 49, 9, 36] Numbers > 5, sorted: [6, 7, 8, 9] Sum: 45, Min: 1, Max: 9 Any element > 8? True
C# array Copy, Clone & Clear
The Array.Copy method copies elements from a source array to a
destination array. The Clone method creates a new array with the
same elements. The Array.Clear method sets elements to their
default value.
string[] names = ["Jane", "Frank", "Alice", "Tom"];
string[] names2 = new string[4];
Array.Copy(names, names2, names.Length);
Console.WriteLine(string.Join(", ", names2));
string[] names3 = (string[]) names.Clone();
names3[0] = "Beky";
Console.WriteLine(string.Join(", ", names));
Console.WriteLine(string.Join(", ", names3));
string[] names4 = new string[6];
names.CopyTo(names4, 2);
Console.WriteLine(string.Join(", ", names4));
Array.Clear(names2);
Console.WriteLine(string.Join(", ", names2));
int[] vals = [1, 2, 3, 4, 5];
Array.Clear(vals, 1, 3);
Console.WriteLine(string.Join(", ", vals));
In the program, we copy arrays in three ways and then clear them.
Array.Copy(names, names2, names.Length);
The Copy method takes the source array, the destination array,
and the number of elements to copy. The destination must already exist and be
large enough.
string[] names3 = (string[]) names.Clone(); names3[0] = "Beky";
The Clone method returns object, so we cast the
result. The clone is a new array; changing it leaves the original intact. The
copy is shallow: for arrays of reference types, both arrays refer to the same
objects.
names.CopyTo(names4, 2);
The CopyTo method copies all elements to another array, starting
at the given index of the destination.
Array.Clear(names2);
The Clear method does not remove elements; an array cannot
shrink. It sets them to the default value, which is null for
strings. string.Join prints null as an empty string.
Array.Clear(vals, 1, 3);
This overload clears three elements starting at index 1.
$ dotnet run Jane, Frank, Alice, Tom Jane, Frank, Alice, Tom Beky, Frank, Alice, Tom , , Jane, Frank, Alice, Tom , , , 1, 0, 0, 0, 5
Comparing arrays
Arrays do not override equality. The == operator and the
Equals method compare references, not elements. To compare the
contents, we use SequenceEqual.
int[] a = [1, 2, 3]; int[] b = [1, 2, 3]; int[] c = a; Console.WriteLine(a == b); Console.WriteLine(a.Equals(b)); Console.WriteLine(a == c); Console.WriteLine(a.SequenceEqual(b)); Console.WriteLine(a.AsSpan().SequenceEqual(b));
We compare two arrays with the same elements and an array with itself.
Console.WriteLine(a == b); Console.WriteLine(a.Equals(b));
The a and b arrays have equal elements, but they are
two different objects. Both comparisons return false.
Console.WriteLine(a == c);
The c variable refers to the same array as a.
Console.WriteLine(a.SequenceEqual(b)); Console.WriteLine(a.AsSpan().SequenceEqual(b));
The LINQ SequenceEqual method compares the elements one by one.
The span version does the same job and is faster for arrays of primitive
types.
$ dotnet run False False True True True
Source
Arrays - language reference
Array class - .NET API
Collection expressions
In this article we have worked with arrays in C#. We have created and initialized arrays, accessed and modified their elements, used multidimensional and jagged arrays, and sorted, searched, copied, and compared arrays. See also the C# ArraySegment, C# List, and C# LINQ articles.
Author
List all C# tutorials.