C# Array Slices Example

In this source code example, we will demonstrate how to use Slices in an Array in C#.

We can use the .. operator to get array slices. A range specifies the start and end of a range. The start of the range is inclusive, but the end of the range is exclusive. It means that the start is included in the range but the end is not included in the range.

C# Array Slices Example

The below C# program works with array ranges:
using System;

public class ArrayDemo
{
    public static void Main(string[] args)
    {
        int[] vals2 = vals[1..5];
        Console.WriteLine("[{0}]", string.Join(", ", vals2));
        
        int[] vals3 = vals[..6];
        Console.WriteLine("[{0}]", string.Join(", ", vals3));
        
        int[] vals4 = vals[3..];
        Console.WriteLine("[{0}]", string.Join(", ", vals4));
    }
}

Output:

[2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[4, 5, 6, 7]

We create an array slice containing elements from index 1 to index 4:

        int[] vals2 = vals[1..5];
If the start index is omitted, the slice starts from index 0:
        int[] vals3 = vals[..6];

If the end index is omitted, the slice goes until the end of the array:

        int[] vals4 = vals[3..];

Comments