Arrays

Creating an array

An array is a fixed number of elements of one type, and the length is decided when it is created. Three ways to write one:

int[] a = new int[3]; int[] b = { 5, 3, 9, 1 }; int[] c = new[] { 1, 2, 3 }; Console.WriteLine($"{a.Length} {b.Length} {c.Length}"); Console.WriteLine(b[0]);

dotnet run

3 4 3
5

new int[3] fills the array with the default value of the element type, which is 0 for a number and null for a reference type. The braces form is the short one, and new[] lets the compiler infer the element type from the values.

The index runs from 0 to Length - 1. A negative index or one past the end throws IndexOutOfRangeException at run time, and the compiler cannot check it because the index is a value.

Length, Sort, IndexOf and Copy

int[] numbers = { 5, 3, 9, 1 }; Console.WriteLine(numbers.Length); Console.WriteLine(numbers[0]); Array.Sort(numbers); Console.WriteLine(string.Join(",", numbers)); Console.WriteLine(Array.IndexOf(numbers, 9)); int[] copy = new int[numbers.Length]; Array.Copy(numbers, copy, numbers.Length); copy[0] = 99; Console.WriteLine($"{numbers[0]} {copy[0]}"); Console.WriteLine(numbers[^1]);

dotnet run

4
5
1,3,5,9
3
1 99
9

Array.Sort rearranges the array in place. IndexOf returns the position of the first equal element or -1. Array.Copy copies values, so writing into the copy leaves the original at 1 — a value copy, unlike the next section.

numbers[^1] is the index-from-the-end operator: one from the end is the last element. It is sugar for numbers[numbers.Length - 1] and works with ^2, ^3 and so on.

An array is a reference

An array is a reference type, so an assignment copies the reference and not the elements. To copy the elements, copy them.

int[] first = { 1, 2, 3 }; int[] second = first; second[0] = 99; Console.WriteLine($"{first[0]} {second[0]}"); int[] third = (int[])first.Clone(); third[0] = 7; Console.WriteLine($"{first[0]} {third[0]}");

dotnet run

99 99
99 7

The first line shows the sharing and the second the copy: Clone returns a new array of the same length, and a write into it is invisible through first. A method that takes an array can therefore change the caller array, which is the same rule the lesson on value and reference types states for a class.

Jagged and rectangular

A two-dimensional array has two forms, and they are different types:

int[][] jagged = new int[2][]; jagged[0] = new[] { 1, 2 }; jagged[1] = new[] { 3 }; int[,] grid = { { 1, 2 }, { 3, 4 } }; Console.WriteLine(jagged[0].Length + jagged[1].Length); Console.WriteLine($"{grid.GetLength(0)}x{grid.GetLength(1)}"); Console.WriteLine(grid[1, 0]);

dotnet run

3
2x2
3

int[][] is an array of arrays: each row has its own length, and jagged[0].Length is 2 while jagged[1].Length is 1. int[,] is one block with a fixed number of rows and columns, indexed by [row, column].

A jagged array is the usual choice for a table with rows of different lengths, and it is also the faster one to index, because each row is a plain array. A rectangular array is one allocation and is easier to pass around when every row has the same width.

Exercises

  1. Read numbers[4] of a four-element array. Which exception do you get, and at which line?
  2. Sort the strings { "beta", "Alpha", "gamma" } and print them. Which order did you get?
  3. Copy an array with Clone, then write into each copy. Which original changes?
  4. Turn the jagged array into a rectangular one and print grid.Length. Why is it not the number of elements?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does new int[3] put into the array?

    Answer

    Three zeroes, the default value of int

    An array of a value type is filled with the default value of that type, which is 0 for int.

  2. What does this program print? int[] numbers = { 1, 2, 3 }; Console.WriteLine(numbers[^1]);

    Answer

    3

    ^1 counts from the end, so it names the last element, which is 3.

  3. What does this program print? int[] first = { 1, 2, 3 }; int[] second = first; second[0] = 9; Console.WriteLine(first[0]);

    Answer

    9

    The assignment copies the reference, so both names reach the same array and the write is visible through both.

  4. What does Array.IndexOf return when the value is not in the array?

    Answer

    -1

    IndexOf returns the position of the first match and -1 when there is none, which is why the result is tested against -1.

  5. What does this program print? int[] numbers = { 4, 2, 3 }; Array.Sort(numbers); Console.WriteLine(string.Join("-", numbers));

    Answer

    2-3-4

    Sort rearranges in place in ascending order, and the join prints the new order.

  6. What is the difference between int[][] and int[,]?

    Answer

    int[][] is an array of arrays with rows of any length; int[,] is one block of rows and columns

    The first form allocates a separate array per row, so the lengths may differ; the second is one rectanglar block.

  7. What does this program print? int[] a = new int[2]; Console.WriteLine(a[0]); Console.WriteLine(a.Length);

    Answer

    0 / 2

    The array starts filled with zeroes and reports its length, so both lines print a number.

  8. What happens when an index is outside the length of the array?

    Answer

    IndexOutOfRangeException at run time

    The index is a run-time value, so the check happens when the element is read, and a bad one throws.

  9. What does this program print? int[,] grid = { { 1, 2 }, { 3, 4 } }; Console.WriteLine(grid.Length);

    Answer

    4

    Length of a multi-dimensional array counts every element, so 2 rows of 2 give 4; GetLength(0) gives the rows.

  10. Which copy keeps the two arrays independent?

    Answer

    Array.Copy or Clone, which copy the elements

    A new array with copied elements is independent; an assignment or a parameter copies only the reference.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev