Skip to content

CSharp Operator Index Range

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Індекси з кінця та діапазони

Довідник C# · Практичне керівництво

^1 позначає останній елемент. Діапазон виключає праву межу; .. без меж означає весь підтримуваний об’єкт.

Простий приклад (Example.cs)

Збережіть цей приклад окремо як Example.cs. Запускайте його незалежно від інших прикладів на сторінці.

Example.cs:

// PROJECT-EXAMPLE
int[] values = [10, 20, 30];
System.Console.WriteLine(values[^1]);
System.Console.WriteLine(string.Join(",", values[..2]));

Результат:

30
10,20

Синтаксис

items[^1] / items[start..end]

Приклад 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        int[] values = [10, 20, 30, 40];
        Console.WriteLine(values[^1]);
        Console.WriteLine(string.Join(",", values[1..3]));
    }
}

Приклад 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        string name = "archer";
        Console.WriteLine(name[..3]);
        Console.WriteLine(name[^2..]);
    }
}

Офіційне джерело: Microsoft Learn.

Clone this wiki locally