Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 182 ยท Collections

Arrays

Learn C# arrays - creating and initializing, indexing, Length, multidimensional vs jagged arrays, Array.Sort, Copy, Resize, IndexOf, covariance pitfalls and array vs List.

An array is a fixed-size, numbered row of values that all have the same type. If a program needs seven temperatures, a hundred scores or the pixels of an image, declaring a hundred separate variables is impossible. An array gives you one name and a position number to choose a value: scores[0], scores[1], and so on.

Arrays are the most basic collection in .NET, and nearly every other collection (List<T>, Dictionary<TKey, TValue>, StringBuilder) is built on top of them. In this lesson you will create and fill arrays, read and change elements, loop over them, use the helper methods of the Array class, work with rows and grids (multidimensional and jagged arrays), and learn pitfalls such as shared references and array covariance.

Creating and initializing arrays

An array's type is the element type followed by []. Arrays are reference types: the variable holds a reference to the array object on the heap. You create one with new and a length, or by listing the values.

C# Four ways to create an array

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.

When you only give a length, every element starts with its type's default value: 0 for numbers, false for bool, '\0' for char, and null for reference types such as string. Collection expressions like [1, 2, 3] are covered in more detail in Collection Expressions and Spread.

Indexing, Length and loops

Elements are numbered from 0. An array of length n has valid indices 0 to n - 1. The Length property gives the number of elements and never changes for that array. Using an invalid index throws an IndexOutOfRangeException at run time.

C# Reading, writing and looping (fails on purpose)

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.

The last line crashes with Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array. after the average and the four scores have been printed. Use for when you need the index or want to change elements, and foreach when you only read them. scores[^1] is the "index from end" syntax from Ranges and Indices.

The runtime checks every index. That costs a little speed but protects you from the memory corruption that out-of-range writes cause in some other languages. The JIT removes many of those checks in simple loops such as for (i = 0; i < a.Length; i++).

Arrays are reference types

Assigning one array variable to another does not copy the elements. Both variables point at the same array:

C# Two names for one array

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.

== on arrays compares references, not contents. To compare contents, use SequenceEqual from LINQ. Clone() makes a shallow copy: if the elements are themselves reference types, the copy holds the same objects.

The Array class: sort, search, copy, resize

Every array inherits from System.Array, which provides static helpers:

C# Sort, Reverse, IndexOf, BinarySearch

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.

Array.Sort changes the array in place. Array.BinarySearch is much faster than a linear search on big arrays, but it only gives correct answers when the array is already sorted. When the item is missing it returns a negative number.

Copying and resizing

An array's length cannot change. Array.Resize does not grow the array; it creates a new array of the requested size, copies the old elements and updates your variable to point to it:

C# Copy and Resize

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.

Because resizing copies everything, calling it in a loop is slow (each call is O(n)). If you need a collection that grows, use List<T>, which manages growth for you.

Multidimensional arrays

A rectangular (multidimensional) array is a grid with a fixed number of rows and columns. Use commas inside the brackets:

C# A 2D array

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.

Length gives the total count of all elements (12 here), Rank the number of dimensions, and GetLength(d) the size of dimension d. Rectangular arrays are compact, but they have drawbacks: every row has the same width, they are slower than single-dimensional arrays in many cases, and they don't work with many APIs and LINQ methods.

Three or more dimensions

Add another comma for each extra dimension. An int[,,] is a "cube": several tables stacked on top of each other, such as sales per store, per month, per product. GetLength(0), GetLength(1) and GetLength(2) give the size of each dimension.

C# A 3D array

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.

Each element is reached with one index per dimension. Beyond three dimensions the code gets hard to read; a small class or record per item is usually clearer.

Jagged arrays: arrays of arrays

A jagged array is an array whose elements are themselves arrays, so rows can have different lengths. You create the outer array first and then each row:

C# A jagged array (triangle)

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.

You read an element with two index operators: triangle[row][col]. In practice jagged arrays are usually faster and more flexible than int[,] because each row is a normal one-dimensional array, which the JIT optimizes well. Use int[,] when a true fixed rectangle makes the code clearer (a chess board, a matrix) and int[][] when rows differ or performance matters.

Array covariance: a runtime trap

Arrays of reference types are covariant: a string[] can be assigned to an object[] variable. That seems friendly, but it makes some writes unsafe, so the runtime checks every store into such an array:

C# Array covariance (fails on purpose)

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.

The program compiles but throws System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at the second store. Lists and generic collections do not have this problem (List<string> cannot be assigned to List<object>), which is one reason to prefer them in new APIs. Covariance does not apply to value-type arrays: int[] cannot become object[].

Arrays versus List<T>

Array List<T>
Size Fixed at creation Grows and shrinks
Add/remove Not possible (resize = copy) Add, Insert, Remove
Access a[i], very fast list[i], very fast
Multiple dimensions Yes No (use List<List<T>>)
Typical use Fixed data, buffers, parameters, Main(string[] args) General-purpose sequences

A good rule: use an array when the size is known and will not change (days of the week, a fixed-size buffer, results of Split), otherwise use a List<T>.

Common mistakes

  • Off-by-one errors: the last valid index is Length - 1, not Length.
  • Forgetting that the array is shared after assignment or when passing to a method. Methods that receive an array can change its contents (see Parameters).
  • Using == to compare contents.
  • Searching an unsorted array with BinarySearch.
  • Calling Resize in a loop instead of using a List<T>.
  • Writing to an array of reference-type default null elements and then reading properties: an Employee[] created with new Employee[3] contains three nulls, not three employees.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the valid indices of an array created with new int[5]?

    Arrays are zero-based. A length of 5 gives indices 0, 1, 2, 3 and 4. Index 5 throws IndexOutOfRangeException.
  2. 2. What does int[] b = a; do, where a is an int[]?

    Arrays are reference types, so assignment copies the reference. Changes through b are visible through a.
  3. 3. What does Array.Resize(ref data, 10) really do?

    An array's size can never change. Resize allocates a new array and copies, so it is O(n) and the old array is no longer used by your variable.
  4. 4. How does a jagged array int[][] differ from a rectangular array int[,]?

    A jagged array stores separate row arrays, so each row can have its own length. A rectangular array is one block with a fixed width for every row.
  5. 5. Why can this throw at run time? object[] items = new string[2]; items[0] = 5;

    Because arrays of reference types are covariant, the compiler allows the store, but the runtime check detects the wrong type and throws ArrayTypeMismatchException.

Summary

  • An array is a fixed-size, zero-based sequence of same-typed elements; Length is its size.
  • Create with new int[n], { ... } or [ ... ]; unset elements hold the type's default value.
  • Arrays are reference types: assignment shares, Clone() or Array.Copy copies, == compares references.
  • Array.Sort, Reverse, IndexOf, BinarySearch, Copy, Resize and Clear cover everyday work; Resize allocates a new array.
  • int[,] is a rectangle, int[][] is an array of arrays and is usually faster and more flexible.
  • Covariance of reference-type arrays can cause ArrayTypeMismatchException; prefer List<T> when the size changes.

Next: List of T