Skip to content

ES CSharp Keyword stackalloc

Codex edited this page Oct 11, 2026 · 2 revisions

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

C#: stackalloc

Manual C# · Guía Práctica

Asigna un búfer en la pila de la llamada actual; permite la forma de puntero o tramo. El tamaño del buffer debe ser limitado.

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

Example.cs:

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

Resultado:

5

Sintaxis

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

En .csproj, establezca true. Para los datos administrados, normalmente es más fácil trabajar con Span sin punteros sin formato.

Ejemplo 1: forma básica

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

Ejemplo 2: otra forma práctica

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

Fuente oficial: Microsoft Aprender.

Clone this wiki locally