Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

stackalloc: riferimento pratico

stackalloc: riferimento pratico: stackalloc riserva un buffer contiguo nello stack frame corrente, di solito come Span<T>.

Versione: C# language; verified against C# 14 reference

Sintassi

stackalloc /* grammar-specific form */

stackalloc riserva un buffer contiguo nello stack frame corrente, di solito come Span.

Usalo per buffer piccoli e di breve durata con dimensione controllata.

Una dimensione grande o derivata da input non attendibile può causare stack overflow.

La memoria scade con lo scope e, a seconda della forma, può non essere inizializzata.

Il programma completo usa realmente stackalloc; lo stdout esatto atteso è 3.

Esempi

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

Span<int> values = stackalloc[] { 1, 2, 3 }; Console.WriteLine(values.Length);

Risultato

3

Il programma completo usa realmente `stackalloc`; lo stdout esatto atteso è `3`.

Fonti