Skip to content

EN CSharp Memory Unsafe

Codex edited this page Oct 11, 2026 · 2 revisions

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

Memory: ref, Span, ref struct and unsafe

Manual C# · Examples UO

Span<T> and ReadOnlySpan<T> give a view over the memory without necessarily copying. ref-return and ref-local variable allow you to work with an existing storage location. The compiler controls the lifetime of references. ref struct cannot be used as a regular heap field; the limits around await and yield depend on the allowed lifetime.

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
System.Span<int> values = stackalloc int[] { 2, 3 };
System.Console.WriteLine(values[0] + values[1]);

Result:

5
static int SumSmall()
{
    Span<int> values = stackalloc int[] { 1, 2, 3 };
    int total = 0;
    foreach (int value in values) total += value;
    return total;
}
UO.Print(SumSmall().ToString());

unsafe permits pointer operations when the compilation allows unsafe blocks. fixed pins movable managed data for the duration of its block, preventing the garbage collector from relocating it while a pointer is used. These language features do not change the game world’s ownership rules.

// PROJECT-EXAMPLE
namespace UserTools;

public static class PointerExample
{
    public static unsafe int ReadLocal()
    {
        int value = 42;
        int* address = &value;
        return *address;
    }
}

Official documentation: Memory: ref, Span, ref struct and unsafe - Microsoft Learn.

Clone this wiki locally