Jump to content
Wikibooks The Free Textbook Project

C# Programming/Keywords/stackalloc

From Wikibooks, open books for an open world
The latest reviewed version was checked on 16 April 2020. There are template/file changes awaiting review.

The keyword stackalloc is used in an unsafe code context to allocate a block of memory on the stack.

int*fib=stackallocint[100];

In the example above, a block of memory of sufficient size to contain 100 elements of type int is allocated on the stack, not the heap; the address of the block is stored in the pointer fib. This memory is not subject to garbage collection and therefore does not have to be pinned (via fixed). The lifetime of the memory block is limited to the lifetime of the method in which it is defined (there is no way to free the memory before the method returns).

stackalloc is only valid in local variable initializers.

Because Pointer types are involved, stackalloc requires unsafe context. See Unsafe Code and Pointers.

stackalloc is similar to _alloca in the C run-time library.

Note* - From MSDN



C# Keywords
Special C# Identifiers (Contextual Keywords)
Contextual Keywords (Used in Queries)

AltStyle によって変換されたページ (->オリジナル) /