0Pricing
C# Academy · Lesson

Ranges with Arrays and Strings

Slice arrays, spans, and substrings.

Slicing Arrays

The most common use of ranges is slicing arrays. array[1..3] returns a new array containing the selected elements.

using System;

int[] data = { 10, 20, 30, 40, 50 };
int[] middle = data[1..3];
Console.WriteLine(string.Join(",", middle)); // 20,30

Array Slices Are Copies

For arrays, a range slice allocates a new array and copies the elements. Mutating the slice does not affect the original.

using System;

int[] original = { 1, 2, 3, 4 };
int[] slice = original[0..2];
slice[0] = 99;
Console.WriteLine(original[0]); // 1 (unchanged)
Console.WriteLine(slice[0]);    // 99

All lessons in this course

  1. The Index Type and ^ Operator
  2. The Range Type and .. Operator
  3. Ranges with Arrays and Strings
  4. Custom Types Supporting Ranges
← Back to C# Academy