Skip to content

EN CSharp Keyword stackalloc

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: stackalloc

Handbook C# · Practical Guide

Allocates a buffer on the stack of the current call; allows pointer or span form. The buffer size must be limited.

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

Syntax

Span<int> values = stackalloc int[3];

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)
    {
        Span<int> values = stackalloc int[3];
        values[0] = 2; values[1] = 4; values[2] = 8;
        int sum = 0; foreach (int value in values) sum += value;
        Console.WriteLine(sum);
    }
}

Official source: Microsoft Learn.

Clone this wiki locally