Skip to content

CSharp Keyword unsafe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: unsafe

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

Дозволяє pointer-синтаксис у визначеній області. Компіляція звичайного проєкту потребує AllowUnsafeBlocks.

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

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

Example.cs:

// PROJECT-EXAMPLE
unsafe
{
    int value = 3;
    int* pointer = &value;
    *pointer = 7;
    System.Console.WriteLine(value);
}

У проєкті ввімкніть <AllowUnsafeBlocks>true</AllowUnsafeBlocks>. Покажчик чинний лише в показаній області.

Результат:

7

Синтаксис

unsafe { Type* pointer = ...; }

У .csproj задайте true. Для managed-даних зазвичай простіше працювати через Span без сирих покажчиків.

Приклад 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)
    {
        unsafe { int* values = stackalloc int[2]; values[0] = 3; values[1] = 7; Console.WriteLine(values[0] + values[1]); Console.WriteLine(sizeof(int)); }
    }
}

Приклад 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)
    {
        int[] values = [2, 4, 6];
        unsafe { fixed (int* pointer = values) { pointer[1] = 9; Console.WriteLine(*(pointer + 1)); Console.WriteLine(sizeof(long)); } }
        Console.WriteLine(values[1]);
    }
}

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

Clone this wiki locally