Skip to content

EN CSharp Keyword safe

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: safe

Handbook C# · Practical Guide

Preview modifier of the updated memory safety model: the author explicitly marks the declaration as not requiring an unsafe context of the caller.

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
class ManagedValue { public int Count { get; set; } }

This short example uses C# 14. It does not implement the preview construct safe, which is unavailable here.

Syntax

public static safe extern int Method();

This is a preview of C# 15 / .NET 11. The official rules require LangVersion=preview and separate enabling of updated-memory-safety-rules for their application. Current C# 14 does not support these declarations.

Status: preview; the current configuration C# 14 / .NET 10 does not support these examples.

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)
    {
        Console.WriteLine(Native.GetCurrentProcessId());
    }
}
public static class Native { [DllImport("kernel32.dll")] public static safe extern uint GetCurrentProcessId(); }

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)
    {
        Union value = new() { Integer = 1065353216 };
        Console.WriteLine(value.Real);
    }
}
[StructLayout(LayoutKind.Explicit)] public struct Union { [FieldOffset(0)] public safe int Integer; [FieldOffset(0)] public safe float Real; }

Official source: Microsoft Learn.

Clone this wiki locally