Skip to content

IT CSharp Keyword stackalloc

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: stackalloc

Manuale C# · Guida pratica

Alloca un buffer nello stack della chiamata corrente; consente il formato puntatore o span. La dimensione del buffer deve essere limitata.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

// PROJECT-EXAMPLE
System.Span<int> values = stackalloc int[] { 2, 3 };
System.Console.WriteLine(values[0] + values[1]);

Risultato:

5

Sintassi

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

In .csproj, imposta true. Per i dati gestiti, in genere è più semplice utilizzare Span senza puntatori non elaborati.

Esempio 1: forma base

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

Esempio 2: un'altra forma pratica

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

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally