Skip to content

EN CSharp Keyword unsafe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: unsafe

Handbook C# · Practical Guide

Allows pointer syntax in the specified scope. Compiling a normal project requires AllowUnsafeBlocks.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

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

Enable <AllowUnsafeBlocks>true</AllowUnsafeBlocks> in the project. The pointer is valid only within the shown scope.

Result:

7

Syntax

unsafe { Type* pointer = ...; }

In .csproj, set true. For managed data, it's usually easier to work through Span without raw pointers.

Example 1: simple form

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)); }
    }
}

Example 2: another practical form

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]);
    }
}

Official source: Microsoft Learn.

Clone this wiki locally