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]);- Expected output: 40 99,30 20
- ^1 denotes the last element; the range ends before that element. Because this is an array slice, modifying middle leaves data unchanged.
- 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