Lesson 10 of 24

In progress

Course progress

C# and .NET

Arrays and spans

Create fixed-size arrays, use Array methods and range syntax, and recognise when a list or a span is the better fit.

An array holds a fixed number of elements of one type. It is the simplest collection, the one the others are built on, and the right choice when the size is known and does not change.

What you will learn

  • Create arrays and index them safely.
  • Use Array helpers and range syntax.
  • Decide between an array, a list and a span.

Creating

int[] scores = new int[5];              // five zeros
string?[] names = new string?[3];       // three nulls
int[] values = { 4, 8, 15, 16, 23 };    // collection initialiser
int[] copied = new int[values.Length];
Array.Copy(values, copied, values.Length);

Elements take the type’s default: 0, false or null. values.Length is a property, and it is fixed at creation.

A jagged array is an array of arrays, and each row can have its own length:

int[][] jagged = new int[3][];
jagged[0] = new[] { 1, 2 };
jagged[1] = new[] { 3 };

A multidimensional array has a rectangular shape and a different access syntax:

int[,] grid = new int[3, 4];
grid[1, 2] = 7;
Console.WriteLine(grid.GetLength(0));   // 3

Jagged arrays are more common in application code because each row can grow independently; rectangular arrays suit mathematical data with a fixed shape.

Indexing and bounds

int[] values = { 10, 20, 30 };
Console.WriteLine(values[2]);    // 30
Console.WriteLine(values[^1]);   // 30, last element
Console.WriteLine(values[^2]);   // 20

Indexes run from 0 to Length - 1. ^1 means "one from the end", which avoids values[values.Length - 1] everywhere.

An out-of-range index throws IndexOutOfRangeException. There is no silent read of adjacent memory, which is one of the safety properties C# gives you.

Ranges produce a new array or a slice:

int[] middle = values[1..];        // { 20, 30 }
int[] firstTwo = values[..2];      // { 10, 20 }

A range on an array allocates a new array. On a Span<T>, it does not.

Array helpers

int[] numbers = { 5, 2, 9, 1 };
Array.Sort(numbers);
Console.WriteLine(string.Join(", ", numbers));    // 1, 2, 5, 9
int index = Array.BinarySearch(numbers, 5);
Console.WriteLine(index);                          // 2
Array.Reverse(numbers);
Array.Fill(numbers, 0);

Array.Sort sorts in place. BinarySearch requires a sorted array and returns a negative value when the element is absent, encoding the insertion point. Array.Fill sets every element.

string.Join is the readable way to print an array; Console.WriteLine(numbers) prints the type name, not the contents.

For searching unsorted data, Array.IndexOf returns -1 when not found, which is easy to use and easy to forget to check.

Spans: slices without allocation

int[] values = { 1, 2, 3, 4, 5 };
Span<int> slice = values.AsSpan(1, 3);
slice[0] = 20;
Console.WriteLine(values[1]);   // 20, the slice writes through

A Span<T> is a view over existing memory: no copy, no allocation. ReadOnlySpan<char> is what string parsing uses internally, and it lets you slice text without creating substrings.

ReadOnlySpan<char> text = "pen,book,lamp".AsSpan();
int comma = text.IndexOf(',');
var first = text[..comma];

That is the difference between parsing a large file with a few allocations and parsing it with thousands. For everyday code, strings are fine; for a hot path, spans are the tool.

Arrays as parameters

Arrays are reference types, so a method receives a reference and can change the elements:

static void Double(int[] values)
{
for (int i = 0; i < values.Length; i++)
{
values[i] *= 2;
}
}

Calling Double(scores) changes the caller’s array. If a method must not change its input, take a ReadOnlySpan<int> or IReadOnlyList<int>, which makes the intent part of the signature.

params lets a method accept a variable number of arguments:

static int Sum(params int[] values) => values.Sum();
Sum(1, 2, 3);
Sum();

The empty call passes an empty array, so the method must handle zero elements.

Memory and locality

An array of value types stores the elements contiguously, so iterating it walks memory in order. That is why an int[] is faster than a List<int> in a tight numeric loop: the list also stores its elements contiguously, but the extra method calls and bounds checks add up at scale.

An array of reference types stores references contiguously and the objects elsewhere, so the loop jumps around memory. That is one reason object-heavy code is slower than the equivalent code over numbers, and why spans and structs matter in performance work.

For ordinary application code, use whichever type reads best. Reach for arrays and spans when a profile shows the loop matters.

Arrays versus lists

Arrays are fixed-size, allocation-efficient and required by some APIs. List<T> grows, has Add and Remove, and is what most application code should use.

Convert when the boundary needs it:

List<int> list = new List<int> { 1, 2, 3 };
int[] array = list.ToArray();
List<int> back = new List<int>(array);

ToArray copies, so do it at the boundary rather than in a loop.

Comparing arrays with ==. It compares references, so two arrays with equal contents are not equal. Use SequenceEqual or StructuralComparisons for nested arrays.

Create an array of five prices, double each in place, then print the last two with range syntax and the total using a span.

Show solution
decimal[] prices = { 45m, 320m, 1200m, 150m, 99m }; for (int i = 0; i < prices.Length; i++) { prices[i] *= 2; } Console.WriteLine(string.Join(", ", prices[^2..])); decimal total = 0m; foreach (decimal price in prices.AsSpan()) { total += price; } Console.WriteLine($"total: {total:F2}");

prices[^2..] takes the last two elements, and AsSpan() iterates the array without an enumerator allocation. The m suffix keeps the arithmetic in decimal, which is what money needs.

Recap

  • Arrays are fixed-size, zero-indexed and throw on out-of-range access.
  • Use ^ and ranges for the end of an array, and Array.Sort/BinarySearch rather than writing them.
  • Spans give you a slice without copying; lists are better when the size changes.

Next, methods: parameters, return values and the overload rules.

What is the difference between an array and a span?
An array owns its memory; a span is a view over memory that already exists, including part of an array or a string.
Can I resize an array?
No. Use `Array.Resize`, which allocates a new array and copies, or switch to a list.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.