Codectionary / Developer documentation / C#

Indices and Ranges

The ^ operator indexes from the end and .. describes a half-open range. Array slicing with a range creates a new array; span slicing creates a view. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

The ^ operator indexes from the end and .. describes a half-open range. Array slicing with a range creates a new array; span slicing creates a view. Use a .NET 8+ console project; replace Program.cs with this C# example.

^1 denotes the last element; the range ends before that element. Because this is an array slice, modifying middle leaves data unchanged.

Syntax

items[^1]; items[start..end]

Examples

Indices and Ranges

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
int[] data = { 10, 20, 30, 40 };
Console.WriteLine(data[^1]);
int[] middle = data[1..^1];
middle[0] = 99;
Console.WriteLine(string.Join(",", middle));
Console.WriteLine(data[1]);
  1. Expected output: 40 99,30 20
  2. ^1 denotes the last element; the range ends before that element. Because this is an array slice, modifying middle leaves data unchanged.
  3. Remember that range ends are exclusive and ^0 is the position after the last element.

Best practices

  • Remember that range ends are exclusive and ^0 is the position after the last element.
  • Use AsSpan when avoiding a copy matters and a short-lived view is suitable.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading