NGWS SDK Documentation  

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

stackalloc

[This is preliminary documentation and subject to change]

Allocates a local array on the stack.

type * ptr = stackalloc type [ expr ];

where:

type
An unmanaged type.
ptr
A pointer name.
expr
An integral expression.

Remarks

An array of expr elements of type type is allocated on the stack, not the heap; the address of the array is stored in pointer ptr. Such an array is not subject to garbage collection and therefore does not have to be pinned (via fixed). The lifetime of the array is limited to the lifetime of the function member in which it is defined.

stackalloc is only valid in local variable initializers.

Because pointers are involved, stackalloc requires unsafe context.

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

Example

using System;   // compile with /unsafe option
class Test {
   public static unsafe void Main() {
      int* fib = stackalloc int[100];
      int* p = fib;
      *p++ = *p++ = 1;
      for (int i=2; i<100; ++i, ++p) *p = p[-1] + p[-2];
      for (int i=0; i<10; ++i) Console.WriteLine (fib[i]);
   }
}

Output

1
1
2
3
5
8
13
21
34
55

See Also

C# Keywords | Operator Keywords