Skip to content

C# Feature - Range operator

The range operator .. creates slices between two indexes and works especially well with arrays, spans, and strings.

C# 8.0 (2019)

string middle = text.Substring(1, text.Length - 2);
string middle = text[1..^1];
int[] lastThree = numbers[^3..];
int[] withoutFirst = numbers[1..];
  • The end index is exclusive.
  • Prefer ranges when slicing is the main idea and not just incidental arithmetic.
  • C# 8 introduced Range and the .. operator.