C# Feature - Range operator
Overview
Section titled “Overview”The range operator .. creates slices between two indexes and works especially well with arrays, spans, and strings.
Introduced In
Section titled “Introduced In”C# 8.0 (2019)
Before
Section titled “Before”string middle = text.Substring(1, text.Length - 2);string middle = text[1..^1];Annotated Example
Section titled “Annotated Example”int[] lastThree = numbers[^3..];int[] withoutFirst = numbers[1..];Gotchas & Best Practices
Section titled “Gotchas & Best Practices”- The end index is exclusive.
- Prefer ranges when slicing is the main idea and not just incidental arithmetic.
Related Features
Section titled “Related Features”Version Notes
Section titled “Version Notes”- C# 8 introduced
Rangeand the..operator.